我有一个使用 .NET SerialPort 类的 C# 应用程序。我用来从串行端口获取数据的代码没什么特别的。关键部分是
//Open the port
comport.BaudRate = myPort.BaudRate;
comport.StopBits = StopBits.One;
comport.DataBits = 8;
comport.Parity = Parity.None;
comport.ReadTimeout = 20000;
comport.PortName = myPort.PortSystemName;
comport.Handshake = Handshake.None;
comport.RtsEnable = true;
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string msg = "";
try
{
msg = comport.ReadExisting();
if (comport.IsOpen)
comport.Close();
}
此代码在 Windows XP 中运行良好。但是,在 Windows 7 上,它会遇到问题,无论发送什么数据,它都只会获取前四个字符。所以在像“123456”这样的字符串中,消息将是“1234”。收集数据的设备是 RFIdeas pcProx,我已验证数据正常。我还验证了 super 终端中的数据看起来没问题。所以我在代码中获取数据的方式一定有些奇怪。帮助!
最佳答案
这与 API 完全一致。它不是,也从来没有保证阅读所有内容:
This method returns the contents of the stream and internal buffer of the SerialPort object as a string. This method does not use a time-out. Note that this method can leave trailing lead bytes in the internal buffer, which makes the BytesToRead value greater than zero.
此外,您需要处理“尚未在内部缓冲区中”——您不能在 BytesToRead 为正时读取。这通常涉及循环和缓冲,直到收到整个消息。
您的工作是读取适量的数据,可以使用行尾等标记,也可以使用长度前缀 header 。
如果它在 XP 上运行得非常好,那只是幸运(也许通过一些时间和/或效率调整)。
以上所有内容同样适用于大多数输入,而不仅仅是串行端口;例如,文件 IO 和网络 IO 的工作原理几乎完全相同。
关于C# 和 SerialPort 类截断数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8929556/