socket粘包、断包、校验

 1 try
 2 {
 3     byte[] buffer = UDPClient.Receive(ref _udpOpto.localPoint);
 4     numberOfBytesRead = 0;
 5     numberOfBytesRead = buffer.Length;
 6     receiveBuffer = new byte[numberOfBytesRead];                    
 7     Array.Copy(buffer, 0, receiveBuffer, 0, numberOfBytesRead);
 8     Array.Clear(buffer, 0, receiveBuffer.Length);
 9 
10     //断包处理
11     if (bodyWriteIndex > 0)
12     {
13         int writeLength = Math.Min(bodyLength, numberOfBytesRead);
14         Array.Copy(receiveBuffer, 0, bodyBuffer, bodyWriteIndex, writeLength);
15         readIndex += writeLength;
16         bodyWriteIndex += writeLength;
17     }
18     //新包/粘包
19     else
20     {
21         //验证帧头
22         string s = BitConverter.ToString(receiveBuffer).Replace("-", "");
23         int i = s.IndexOf("AA01");
24         if (i != 0)
25         {
26             return;
27         }
28         int writeLength = Math.Min(bodyLength, numberOfBytesRead - readIndex);
29         bodyBuffer = new byte[bodyLength];
30         Array.Copy(receiveBuffer, readIndex, bodyBuffer, 0, writeLength);
31         readIndex += writeLength;
32         bodyWriteIndex += writeLength;
33     }
34     Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
35                     
36     //完成一个包
37     if (bodyWriteIndex == bodyLength)
38     {
39         readIndex = 0;
40         bodyWriteIndex = 0;
41         //验收帧头
42         string s = BitConverter.ToString(bodyBuffer).Replace("-", "");
43         int dh = s.IndexOf("AA01");        
44         if (dh == 0)
45         {
46             int dSum = 0;
47             for (int i = 0; i<bodyBuffer.Length - 1; i++)
48             {
49                 dSum += bodyBuffer[i];
50             }
51             //验证校验码
52             if (dSum % 256 == bodyBuffer[82])
53             {
54                 xxModel pm = bufferToModel(bodyBuffer);
55                 Array.Clear(bodyBuffer, 0, bodyBuffer.Length);
56                 //异步
57                 Task.Run(() =>
58                 {
59                     //存储
60                 });
61             }
62         }
63     }
64 }
65 catch (ThreadAbortException ex)
66 {
67     //不作处理          
68 }
69 catch (Exception ex)
70 {
71     LogHelper.WriteLog(LogFile.Error, "[错误信息]:" + ex.ToString());
72 }

 

posted @ 2020-11-24 11:37  X-Jonney  阅读(286)  评论(0编辑  收藏  举报