//针对数据协议:head + len + playload + check 类型 private List<byte> buffer = new List<byte>(4096); private void sp_DataReceived(objectsender, EventArgs e) //sp是串口控件 { int n = sp.BytesToRead; byte[] buf = new byte[n]; sp.Read(buf, 0, n); //1.缓存数据 buffer.AddRange(buf); //2.完整性判断 while (buffer.Count >= 4) //至少包含帧头(2字节)、长度(1字节)、校验位(1字节);根据设计不同而不同 { //2.1 查找数据头 if (buffer[0] == 0x01) //传输数据有帧头,用于判断 { int len = buffer[2]; if (buffer.Count < len + 4) //数据区尚未接收完整 { break; } //得到完整的数据,复制到ReceiveBytes中进行校验 byte[] ReceiveBytes = new byte[len + 4]; buffer.CopyTo(0, ReceiveBytes, 0, len + 4); byte jiaoyan; //开始校验---自定义实现 jiaoyan = this.JY(ReceiveBytes);// if (jiaoyan != ReceiveBytes[len+3]) //校验失败,最后一个字节是校验位 { buffer.RemoveRange(0, len + 4); MessageBox.Show("数据包不正确!"); continue; } buffer.RemoveRange(0, len + 4); ///执行对数据进行处理操作RunReceiveDataCallback(ReceiveBytes); } else //帧头不正确时,记得清除 { buffer.RemoveAt(0); } } }