首页 > 其他 > 详细

socket粘包、断包、校验

时间:2020-11-24 12:28:11      阅读:34      评论:0      收藏:0      [点我收藏+]
 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 }

 

socket粘包、断包、校验

原文:https://www.cnblogs.com/X-Jonney/p/14029355.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!