转自:https://blog.csdn.net/qq_31967569/article/details/83059501
解析消息体 从缓存里取出一个一个完整的数据包
public static byte[] Decode(ref List<byte> cache)
{
//首先要获取长度,整形4个字节,如果字节数不足4个字节
if (cache.Count < 4)
{
return null;
}
//读取数据
MemoryStream ms = new MemoryStream(cache.ToArray());
BinaryReader br = new BinaryReader(ms);
int len = br.ReadInt32();
//根据长度,判断内容是否传递完毕, ms.Length - ms.Position为剩余流长度
if ( ms.Length - ms.Position<len || len < 0)
{
return null;
}
//获取数据,读取4个字节数据
byte[] result = br.ReadBytes(len);
//清空消息池
cache.Clear();
//讲剩余没处理的消息存入消息池
cache.AddRange(br.ReadBytes((int)ms.Length - (int)ms.Position));
return result;
}
BinaryReader.ReadBytes(Int32)
从当前流中读取指定的字节数以写入字节数组中,并将当前位置前移相应的字节数。