110,533
社区成员
发帖
与我相关
我的任务
分享
public void recmessage(byte[] data)
{
if (ThisClient.Connected)
{
//接受消息头(消息校验码4字节 + 消息长度4字节 + 身份ID8字节 + 主命令4字节 + 子命令4字节 + 加密方式4字节 = 28字节)
int HeadLength = 28;
//存储消息头的所有字节数
byte[] recvBytesHead = new byte[HeadLength];
//如果当前需要接收的字节数大于0,则循环接收
while (HeadLength > 0)
{
byte[] recvBytes1 = new byte[28];
//将本次传输已经接收到的字节数置0
int iBytesHead = 0;
//如果当前需要接收的字节数大于缓存区大小,则按缓存区大小进行接收,相反则按剩余需要接收的字节数进行接收
if (HeadLength >= recvBytes1.Length)
{
log.text += "2";
iBytesHead = ThisClient.Receive(recvBytes1, recvBytes1.Length, 0);
log.text += "3";
}
else
{
iBytesHead = ThisClient.Receive(recvBytes1, HeadLength, 0);
}
//将接收到的字节数保存
recvBytes1.CopyTo(recvBytesHead, recvBytesHead.Length - HeadLength);
//减去已经接收到的字节数
HeadLength -= iBytesHead;
}
//接收消息体(消息体的长度存储在消息头的4至8索引位置的字节里)
byte[] bytes = new byte[4];
Array.Copy(recvBytesHead, 4, bytes, 0, 4);
int BodyLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 0));
//存储消息体的所有字节数
byte[] recvBytesBody = new byte[BodyLength];
//如果当前需要接收的字节数大于0,则循环接收
while (BodyLength > 0)
{
byte[] recvBytes2 = new byte[BodyLength < 1024 ? BodyLength : 1024];
//将本次传输已经接收到的字节数置0
int iBytesBody = 0;
//如果当前需要接收的字节数大于缓存区大小,则按缓存区大小进行接收,相反则按剩余需要接收的字节数进行接收
if (BodyLength >= recvBytes2.Length)
{
iBytesBody = ThisClient.Receive(recvBytes2, recvBytes2.Length, 0);
}
else
{
iBytesBody = ThisClient.Receive(recvBytes2, BodyLength, 0);
}
//将接收到的字节数保存
recvBytes2.CopyTo(recvBytesBody, recvBytesBody.Length - BodyLength);
//减去已经接收到的字节数
BodyLength -= iBytesBody;
}
string res = DataPackagesTransform.UnpackDataToStr(recvBytesHead, recvBytesBody);
RecMsg.Enqueue(res);
log.text += "队列加入元素";
}
}
#region 数据接收
private void AsyncRecive()
{
if (ThisClient.Connected)
{
ThisClient.BeginReceive(_recvBytes, 0, _recvBytes.Length, SocketFlags.None, CallbackRecive, ThisClient);
}
}
private void CallbackRecive(IAsyncResult ar)
{
try
{
int lenth = ThisClient.EndReceive(ar);
if (lenth > 0)
{
RecvByte(_recvBytes, lenth);
log.text += string.Format("<color=yellow>_recvBytes的长度是:{0}</color>", lenth);
recmessage(_recvBuffer._allRecvBytes);
}
}
catch (Exception)
{
}
AsyncRecive();
}
#endregion
这里是异步接收消息,接收后解析消息,消息分为消息头和消息体