C# 网络编程的分包粘包的解决方案

 

class Message
    {
        //发送信息
        public byte[] SendData(byte[] message)
        {

            MemoryStream memoryStream = new MemoryStream();//创建一个内存流

            byte[] BagHead = BitConverter.GetBytes(message.Length + 4);//往字节数组中写入包头(包头自身的长度和消息体的长度)的长度

            memoryStream.Write(BagHead, 0, BagHead.Length);//将包头写入内存流

            memoryStream.Write(message, 0, message.Length);//将消息体写入内存流

            byte[] HeadAndBody = memoryStream.ToArray();//将内存流中的数据写入字节数组

            memoryStream.Close();//关闭内存
            memoryStream.Dispose();//释放资源
            
            return HeadAndBody;
        }


       //接收信息
        MemoryStream memoryStream = new MemoryStream();//开辟一个内存流
        public void ReceiveData(byte[] receivedata, int receiveLength)
        {

            memoryStream.Write(receivedata, 0, receiveLength);//将接受到的数据写入内存流中
            byte[] getData = memoryStream.ToArray();//将内存流中的消息体写入字节数组
            int StartIndex = 0;//设置一个读取数据的起始下标
            while (true)
            {
                if (receiveLength > 0)//如果接受到的消息不为0(不为空)
                {
                    int HeadLength = 0;//包头长度(包头+包体)
                    if (getData.Length - StartIndex < 4)//包头接受不完整
                    {
                        HeadLength = -1;
                    }
                    else
                    {
                        //如果包头接受完整  转换成int类型的数值
                        HeadLength = BitConverter.ToInt32(getData, StartIndex);
                    }
                    //包头接受完整但是消息体不完整              //包头接受不完整
                    //↓↓↓↓↓↓↓↓                            ↓↓↓
                    if (getData.Length - StartIndex < HeadLength || HeadLength == -1)
                    {
                        memoryStream.Close();//关闭内存流
                        memoryStream.Dispose();//释放内存资源
                        memoryStream = new MemoryStream();//创建新的内存流
                        memoryStream.Write(getData, StartIndex, getData.Length - StartIndex);//从新将接受的消息写入内存流
                        break;
                    }
                    else
                    {
                        //如果消息(包头+包体)接受完整了,解析数据
                        string str = Encoding.UTF8.GetString(getData, StartIndex + 4, HeadLength - 4);
                        Console.WriteLine("接收到客户端的消息是-----"+HeadLength+"  " + str);

                        StartIndex += HeadLength;//当读取一条完整的数据后,读取数据的起始下标应为当前接受到的消息体的长度(当前数据的尾部或下一条消息的首部)
                    }
                }
            }
        }
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值