110,539
社区成员
发帖
与我相关
我的任务
分享
user.BuffList.InsertByteArray(data); //插入数据包缓冲池
do
{
try
{
byte[] buff = user.BuffList.GetData(); //取出存在的数据包
if (buff == null)
break;
DataHandler(buff, user); //将每个数据包指令进行处理
}
catch
{
//取包异常
}
} while (true);
public class BuffList
{
public object locklist = new object();
public List<byte> ByteList { get; set; }
public BuffList()
{
ByteList = new List<byte>();
}
public void Clecr()
{
lock (locklist)
{
ByteList.Clear();
}
}
public void InsertByteArray(byte[] Data)
{
lock (locklist)
{
ByteList.AddRange(Data);
}
}
public Int16 readint16wgh()
{
byte[] temp = new byte[2];
ByteList.CopyTo(0, temp, 0, 2);
return BitConverter.ToInt16(temp, 0);
}
public enum CmdType
{
XXX = 1101,
}
public byte[] GetData()
{
lock (locklist)
{
if (ByteList.Count > 288)
{
if ((CmdType)readint16wgh() == CmdType.XXX)
{
byte[] temp = new byte[289];
ByteList.CopyTo(0, temp, 0, 289);
if (packet.CheckWGHData(temp))
{
ByteList.RemoveRange(0, 289);
return temp;
}
}
else
{
//包异常,无法正确解析
}
return null;
}
else
{
return null;
}
}
}
}
public void InsertByteArray(byte[] Data)
{
lock (locklist)
{
ByteList.AddRange(Data);
}
}
public delegate void InputHandler(byte[] data, SocketAsyncEventArgs socketAsync);
public InputHandler Input { get; set; }
void BeginReceive(SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success&&e.BytesTransferred>0)
{
byte[] data = new byte[e.BytesTransferred];
Array.Copy(e.Buffer, e.Offset, data, 0, data.Length);
if (this.Input != null)
this.Input.BeginInvoke(data, e, RecevieCallBack, Input);
if (!e.AcceptSocket.ReceiveAsync(e))
{
BeginReceive(e);
}
}
}