我修改了from the example you linked:
要真正让两个端口运行来来回读写,您实际上需要实现两个端口的读写线程。
使用计时器可能是个好主意。
public static void Main()
{
SerialPort SendSerialPort = new SerialPort("Com3", 9600);
SerialPort ReceiveSerialPort = new SerialPort("Com4", 9600);
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
SendSerialPort.Open();
ReceiveSerialPort.Open();
bool _continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
_continue = false;
else
SendSerialPort.WriteLine(String.Format("<{0}>: {1}", name, message));
}
readThread.Join();
SendSerialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = ReceiveSerialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
通常在写入的数据中会有一个开始值和结束值,以告诉另一个端口消息已完成,并且端口也可以验证它们正在读取它们应该读取的数据,通常带有如何处理的命令那个数据。 (超出这个问题的范围)。
端口的初始化也很重要。
我更喜欢使用默认构造函数(仅限偏好)
SerialPort Constructor ()
然后像这样设置任何值:
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
所有的构造函数都会给出这些值:
This constructor uses default property values when none are specified.例如DataBits属性默认为8,Parity属性默认为None枚举值,StopBits属性默认为1,默认端口名称为COM1。
即使是握手也有默认值。如果你look at the source code.
private const Handshake defaultHandshake = Handshake.None;