文章内容有错,请直接关闭~~~不要看了。丢人。
private static Dictionary<string, Packet> cache = new Dictionary<string, Packet>();
private static Dictionary<string, object> lockers = new Dictionary<string, object>();
public List<pkReturn> Package(ChannelReceiveEventArgs e)
{ byte[] data = new byte[e.Data.Count];
Buffer.BlockCopy(e.Data.Array, , data, , e.Data.Count);
int leng = e.Data.Count; if (!lockers.ContainsKey(e.Channel.ID)) lockers[e.Channel.ID] = new object(); //创建锁
lock (lockers[e.Channel.ID])
{
if (data != null)
{
string id = e.Channel.ID;
try
{
if (cache.ContainsKey(id))
{//如果客户端ID存在,就把接收到的字节,和之前的字节合起来
cache[id].BufferTemp = coder.UnionBytes(cache[id].BufferTemp, data);
}
else
{//如果客户端ID不存在集合内,就新建一个放入集合
Packet pk = new Packet();
cache[id] = pk;
cache[id].BufferTemp = new byte[leng];
Buffer.BlockCopy(data, , cache[id].BufferTemp, , data.Length);//拷贝数据
}
//循环处理包
List<pkReturn> lists = new List<pkReturn>();
cache[id].BufferCom = null;
do
{
pkReturn model = new pkReturn();
if (cache[id].BufferTemp.Length >= ) //1-4字节包大小 4-6两字节指令
{
byte[] sizetemp = new byte[];//大小
Buffer.BlockCopy(cache[id].BufferTemp, , sizetemp, , );
int size = (int)BitConverter.ToUInt32(sizetemp, );
size = size + ;
byte[] cmd = new byte[];//指令
Buffer.BlockCopy(cache[id].BufferTemp, , cmd, , );
if (size < && size > )
{
model.PkSize = size;
model.Cmd = (int)BitConverter.ToUInt32(cmd, );
}
else
{
e.Channel.Dispose();
Remove(id);//小于0 有问题 要清理掉客户端
lists.Clear();
break;
}
//解析包
byte[] tempbytes = new byte[size];
if (size < cache[id].BufferTemp.Length)
{ Buffer.BlockCopy(cache[id].BufferTemp, , tempbytes, , size);//拷贝一个完整包 byte[] temp = new byte[cache[id].BufferTemp.Length - size];//保存剩下的字节
Buffer.BlockCopy(cache[id].BufferTemp, size, temp, , cache[id].BufferTemp.Length - size);
cache[id].BufferTemp = temp; model.Bytes = coder.UnifyDecrypt(tempbytes);//对完整包解密
lists.Add(model);
}
else if (size == cache[id].BufferTemp.Length)
{
Buffer.BlockCopy(cache[id].BufferTemp, , tempbytes, , size);//根据获得大小拷贝字节
model.Bytes = coder.UnifyDecrypt(tempbytes);//对完整包解密
lists.Add(model);
cache[id].BufferTemp = null;//清空数据缓冲区
break;
}
else if (size > cache[id].BufferTemp.Length)
{//如果包头标记大小大于缓冲区大小,跳出
break;
}
else
{
Console.WriteLine("任何条件都不符合");
} }
else
{
break;
}
} while (true);
return lists;
}
catch (Exception ex)
{
Remove(id);
e.Channel.Dispose();
Console.WriteLine("分包解析函数异常:" + ex.Message + " 定位:" + ex.StackTrace);
throw new ArgumentException("分包解析函数异常 定位:"+ex.Message);
}
}
else
{
Console.WriteLine("data 为null");
throw new ArgumentException("分包解析函数异常 data 为null");
//return null;
}
}
}