北京地标(DB11) 据接收器.
/// <summary> /// DB11协议拆包器 /// </summary> public class SplictProtocol { /// <summary> /// 用于处理数据协义的功能 /// </summary> List<byte> bytes = new List<byte>(5000); private int len = -1; /// <summary> /// 包头 /// </summary> private bool FindPackageHead = false; /// <summary> /// 索引 /// </summary> int index = -1; public List<byte[]> Splict(byte[] arr) { List<byte[]> list = new List<byte[]>(); try { if (arr != null) { //锁处理 lock (bytes) { //开始从队列中取数据 for (int k = 0; k < arr.Length; k++) { //队列有数据 byte b = arr[k]; //如果超过最大接收字节数 if (1000 * 1024 <= bytes.Count) { bytes.Clear(); } //添加到对像集合 bytes.Add(b); //3.从集合的前面开始取数据.找包头,进行拆包 if (bytes.Count >= 24) { if (!FindPackageHead) { for (int i = 0; i < bytes.Count; i++) { if (bytes[i] == 0x23 && (i + 1 < bytes.Count && bytes[i + 1] == 0x23)) { index = i; FindPackageHead = true; break; } } } if (index > -1) { //22 数据单元长度索引 if (bytes.Count > index + 23) { if (len == -1) { int xx = 0; //数据长度 len = new byte[2] { bytes[index + 22], bytes[index + 23] }.ReadUshort(ref xx).SwapUInt16(); } if (bytes.Count > index + len + 24) { var bb = bytes.Skip(index).Take(24 + len + 1).ToArray(); list.Add(bb); //初始化状态 FindPackageHead = false; len = index = -1; //移除所有数据 bytes.Clear(); } } } } } } } else { //Thread.Sleep(1); } } catch (Exception ex) { bytes.Clear(); //初始化状态 FindPackageHead = false; len = index = -1; } return list; } }
时间: 2024-10-24 09:38:09