.net 2.0 串口通讯的问题,SerialPort的ReadBufferSize到底有什么用?
我的程序和一台医疗仪器通讯。通讯建立后,该医疗仪器每次发送一行数据(但我也不确定一行数据是分次发还是一次性发,因为这个程序不是我写的,但从结果上判断,应该是一次性发送的)。结果我的程序一般情况下先收200字节,然后再收48字节(偶尔也会一次性收248字节,所以我判断医疗仪器是一次性发送一行数据)。
我的程序是在ReveiveData事件中接收数据的,另外,ReceivedBytesThreshold属性设置为1。我的程序已经依靠数据侦的首尾标志解决分段接收的问题,但以下疑问在心中,仍无法得到答案
但为什么我的程序是先收200字节,再收48字节?我的ReadBufferSize已经设置为1M了,为何没有效果?还请高手解答。
另:还有没有其它数据接收方式,能够一次性接收完对方一次性发送过来的数据?
请参考一下下面的方法。
技术要点:
(1).首先,SerialPort的ReceivedBytesThreshold先设置成1,表示只要有1个字符送达端口时便触发DataReceived事件
(2).当DataReceived触发时,先把ReceivedBytesThreshold设置成一个比较大的值,达到读取本次端口数据时,不再触发DataReceived.
(3).循环读取端口中的数据,直至读完。
(4).移除读取数据中的非法字符。
(5).触发一个后台线程处理收到的数据。
(6).在finally中把ReceivedBytesThreshold重置回1
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (sender.GetType() != typeof(System.IO.Ports.SerialPort))
{
return;
}
string strReceive = string.Empty;
string strCollect = string.Empty;
System.IO.Ports.SerialPort comPort = (System.IO.Ports.SerialPort)sender;
try
{
comPort.ReceivedBytesThreshold = comPort.ReadBufferSize;
while (true)
{
strReceive = comPort.ReadExisting();
if (string.Equals(strReceive, string.Empty))
{
break;
}
else
{
strCollect += strReceive;
Application.DoEvents();
Thread.Sleep(100);
}
}
strCollect = strCollect.Replace(“\0”, string.Empty);
strCollect = strCollect.Replace(“\r\n”, string.Empty);
strCollect = strCollect.Replace(“\r”, string.Empty);
strCollect = strCollect.Replace(“\n”, string.Empty);
if (!this.bIsHandleCom)
{
this.bIsHandleCom = true;
mReceiveData = strCollect;
if (ReceiveDataParserEvent != null)
ReceiveDataParserEvent(mReceiveData);
if (ThreadReceiveParser != null && !ThreadReceiveParser.IsAlive)
{
ThreadReceiveParser.Start();
}
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
comPort.ReceivedBytesThreshold = 1;
}
}
以上内容节选自CSDN,侵权必删