socket粘包分包处理

public static string Remaning(NetworkStream networkStream)
        {
            string msg = string.Empty;
            int headSize = 4; //包头长度
            int bufferSize = 20; //缓冲区长度
            byte[] headData = new byte[headSize]; //包头数据
            byte[] bufferData = new byte[bufferSize]; //缓冲区数据
            networkStream.Read(headData, 0, headData.Length); //读取包长度
            int dataSize = BitConverter.ToInt32(headData, 0); //数据总长度
            byte[] recvData = new byte[dataSize]; //接收完整数据的缓冲区

            while (dataSize > 0)
            {
                //需要接收的数据大于缓冲区,则按缓冲区大小接收,反之按照剩余的数据大小进行接收
                int offset = dataSize < bufferSize ? dataSize : bufferSize;
                byte[] readData = new byte[offset];
                int readSize = 0; //读取数据的大小
                readSize = networkStream.Read(readData, 0, offset);//将接收到的字节数保存
                readData.CopyTo(recvData, recvData.Length - dataSize);
                dataSize -= readSize;
            }

            msg = Encoding.UTF8.GetString(recvData, 0, recvData.Length);

            Console.WriteLine("MSG:" + msg);


            return msg;
        }

 

posted @ 2020-11-28 17:09  docomo  阅读(158)  评论(0编辑  收藏  举报