Contents

粘包/分包消息处理

Contents
byte[] catchBytes = new byte[1024 * 1024];
int catchNum = 0;
private void HandleReceiveMessage(byte[] bytes, int receiveLength)
{
    //消息ID
    int msgId = 0;
    //消息长度
    int msgLength = -1;
    //当前的索引
    int nowIndex = 0;
    //将接收到的byte写入缓存
    bytes.CopyTo(catchBytes, catchNum);
    catchNum += receiveLength;
    while (true)
    {
        if (catchNum > 8)
        {
            //解析id
            msgId = BitConverter.ToInt32(catchBytes, nowIndex);
            nowIndex += 4;
            //解析长度
            msgLength = BitConverter.ToInt32(catchBytes, nowIndex);
            nowIndex += 4;
        }
        else
        {
            msgLength = -1;
        }
        //粘包
        if (catchNum - 8 >= msgLength && msgLength != -1)
        {

            //解析消息体
            BaseMsg baseMsg = null;
            switch (msgId)
            {
                case 1:
                    PlayerMsg msg = new PlayerMsg();
                    //读取消息
                    msg.Reading(catchBytes, nowIndex);
                    baseMsg = msg;
                    break;
            }
            if (baseMsg != null)
            {
                //receiveMsgQueue.Enqueue(baseMsg);
                Console.WriteLine((baseMsg as PlayerMsg).playerData);
            }
            nowIndex += msgLength;
            if (nowIndex == catchNum)
            {
                catchNum = 0;
                break;
            }
        }
        //分包
        else
        {
            if (msgLength != -1) 
            {
                nowIndex -= 8;
            }  
            //写缓存
            Array.Copy(catchBytes, nowIndex, catchBytes, 0, catchNum - nowIndex);
            catchNum = receiveLength - nowIndex;
        }
    }
}