C# 服务器和客户端通信粘包处理

 

    void ReceiveBack()
    {
        int index = 0;                                           //解析每次报文用的标识
        byte[] arr1 = new byte[2048];
        List<byte> arr3 = new List<byte>();                      // 总的报文集合
        int totalLength = 0;//每次报文的总字节数
        int variableCount = 0;//变量名总字节数
        int nRemainAndNew = 0;//剩余的加上新的
        SocketConnetBack();

        while (true)
        {
            recvLen = clientSocket.Receive(recvData);//接收到的数据
            index = 0;
            for (int k = 0; k < recvLen; k++)
            {
                arr3.Add(recvData[k]);
            }

            nRemainAndNew = arr3.Count;
            arr1 = arr3.ToArray();
            totalLength = BitConverter.ToInt32(arr1, index);//报文的总长
            double remainDataLength = nRemainAndNew;
            while (totalLength <= remainDataLength)
            {
                // 直接处理一个报文
                index += 4;
                variableCount = BitConverter.ToInt32(arr1, index);//变量名总字节数
                index += 4;
                string szVariables = Encoding.ASCII.GetString(arr1, index, variableCount);//变量名
                string[] arrVariables = szVariables.Split('#');//变量名
                index += variableCount;
                this.inputCountnormal = BitConverter.ToInt32(arr1, index);
                index += 4;
                this.varInputListnormal.Clear();
                this.varInputNameListnormal.Clear();
                for (int i = 0; i < this.inputCountnormal; i++)
                {
                    double a = BitConverter.ToDouble(arr1, index);
                    index += 8;
                    VariableAllInfo vai = new VariableAllInfo();
                    vai.dataType = 0;//double
                    vai.strName = arrVariables[i];
                    vai.dValue = a;
                    this.varInputListnormal.Add(vai);
                    this.varInputNameListnormal.Add(vai.strName);
                }
                    
                // 剩余变量
                remainDataLength -= totalLength;
                if (remainDataLength > 4)
                {
                    totalLength = BitConverter.ToInt32(arr1, index);
                }
                else
                {
                    break;
                }
            }
                
            // 添加剩余部分
            if (remainDataLength > 0)
            {
                int nArray3Count = arr3.Count;
                arr3.Clear();
                for (int j = index; j < nArray3Count; j++)
                {
                    arr3.Add(arr1[j]);
                }
            }
            else
            {
                arr3.Clear();
            }            
       }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值