Socket通用TCP通信协议设计及实现(防止粘包,可移植,可靠)

Socket通用TCP通信协议设计及实现(防止粘包,可移植,可靠

 

引文

我们接收Socket字节流数据一般都会定义一个数据包协议。我们每次开发一个软件的通信模块时,尽管具体的数据内容是不尽相同的,但是大体上的框架,以及常用的一些函数比如转码,校验等等都是相似甚至一样的。所以我感觉设计一个通用的通信协议,可以在之后的开发中进行移植实现高效率的开发是很有必要的。另外,本协议结合我自己所了解的通信知识尽可能的提升了可靠性和移植性,可处理类似粘包这样的问题。对于本文中可能存在的问题,欢迎各位大神多多指点。

 

报文设计

         本报文的字段结构分为Hex编码和BCD(8421)编码两种。由于BCD编码的取值范围其实是Hex编码的真子集,也就是所谓的16进制编码中的“ABCDEF”这六个字母对应的数值是在BCD编码中无法取值的。所以我利用这个特点,将报文中的用于标识的不含实际数据的抽象字段用Hex编码,且取值范围在A~F之间。将反应实际数据的字段用BCD编码。这样,具有标识作用的字段与实际数据字段的取值是互不交叉的。这无形中就避免了很多出现的问题,增强了报文的可靠性。例如:我使用”0xFFFF”代表报文起始符,这个取值是不会在任何一个数据字段中出现的,应为它们是BCD编码。也就是是说,字节流缓冲区中只要出现”0xFFFF”我们就可以判断这个是一个数据包的开头(我在实现在缓冲区中找寻数据包算法时还做了另外的控制,进行双重保障)。

         对于正文部分,我设计成了“标识符|数据”成对出现的形式。每个标识符用来指示后面出现的数据的含义,数据字段用于传输真实的数据。这种对的形式,增强了报文的移植性,在新的一次开发到来时,我们只要按需求定义好正文部分的“标识符|数据”对即可。另外,这种设计还增强了发送报文方的灵活性。标识符的存在使得各项数据可以按照任意的顺序发送,没有的数据也可以不发。

         基于以上的这些考虑,我把报文设计成了如下形式:

 

通用报文协议

序号

名称

编码说明

 1

报文起始符

2字节Hex编码    0xFFFF

 2

功能码(报文类型)

2字节Hex编码    0xD1D1

 3

密码

4字节BCD编码    00 00 00 01

 4

长度

2字节BCD编码    正文实际长度

 5

标识符1

2字节Hex编码   自定义数据标识符  0xA001

 6

数据1

N字节BCD编码  N根据实际情况自定义

 7

标识符2

2字节Hex编码   自定义数据标识符  0xA002

 8

数据2

N字节BCD编码  N根据实际情况自定义

 ...

 

 

报文终止符

2字节Hex编码   0xEEEE

 

校验码

校验码前所有字节的CRC校验,生成多项式:X16+X15+X2+1,高位字节在前,低位字节在后。

 

报文示例:

示例背景:发送报文通知远程服务器第1号设备开关的当前状态为开启

需自定义正文部分,含两个字段,设备编号和开关状态

发送的字节数组:255 255 | 209209 | 0 0 0 1 | 0 6 | 160 1 | 1 | 160 2| 0 | 238 238 | 245 40 |

对应含义解释:   起始符FFFF | 功能码D1D1 | 密码00 00 00 01 | 长度(正文)00 06|    标识符A001 | 数据 1 | 标识符A002 | 数据 0 | 报文终止符 EEEE | 校验结果 |

 

粘包问题的解决

针对我的协议,我设计了一个缓冲区中找寻数据包算法,这两者的配合完美的实现了防止粘包,过滤噪声数据等类似的各种令人头疼的问题。此算法思路来自博文点击打开链接 

算法流程图如下:


算法C#代码具体实现:

[csharp]  view plain  copy
 print ?
  1. /// <summary>  
  2.     /// 数据缓冲区  
  3.     /// </summary>  
  4.     public class DataBuffer  
  5.     {  
  6.         //字节缓冲区  
  7.         private List<byte> m_buffer = new List<byte>();  
  8.  
  9.         #region 私有方法  
  10.   
  11.         /// <summary>  
  12.         /// 寻找第一个报头 (0xFFFF)  
  13.         /// </summary>  
  14.         /// <returns>返回报文起始符索引,没找到返回-1</returns>  
  15.         private int findFirstDataHead()  
  16.         {  
  17.             int tempIndex=m_buffer.FindIndex(o => o == 0xFF);  
  18.             if (tempIndex == -1)  
  19.                 return -1;  
  20.             if ((tempIndex + 1) < m_buffer.Count)  //防止越界  
  21.                 if (m_buffer[tempIndex + 1] != 0xFF)  
  22.                     return -1;  
  23.   
  24.             return tempIndex;  
  25.         }  
  26.   
  27.         /// <summary>  
  28.         /// 寻找第一个报尾 (0xEEEE)  
  29.         /// </summary>  
  30.         /// <returns></returns>  
  31.         private int findFirstDataEnd()  
  32.         {  
  33.             int tempIndex = m_buffer.FindIndex(o => o == 0xEE);  
  34.             if (tempIndex == -1)  
  35.                 return -1;  
  36.             if((tempIndex+1)<m_buffer.Count)  //防止越界  
  37.                 if (m_buffer[tempIndex + 1] != 0xEE)  
  38.                     return -1;  
  39.   
  40.             return tempIndex;  
  41.         }  
  42.  
  43.         #endregion  
  44.   
  45.   
  46.         /// <summary>  
  47.         /// 在缓冲区中寻找完整合法的数据包  
  48.         /// </summary>  
  49.         /// <returns>找到返回数据包长度len,数据包范围即为0~(len-1);未找到返回0</returns>  
  50.         public int Find()  
  51.         {  
  52.             if (m_buffer.Count == 0)  
  53.                 return 0;  
  54.   
  55.             int HeadIndex = findFirstDataHead();//查找报头的位置  
  56.   
  57.             if (HeadIndex == -1)  
  58.             {  
  59.                 //没找到报头  
  60.                 m_buffer.Clear();  
  61.                 return 0;   
  62.             }  
  63.   
  64.             if (HeadIndex >= 1)//不为开头移掉之前的字节  
  65.                 m_buffer.RemoveRange(0, HeadIndex);  
  66.   
  67.             int length = GetLength();  
  68.   
  69.             if (length==0)  
  70.             {  
  71.                 //报文还未全部接收  
  72.                 return 0;  
  73.             }  
  74.   
  75.             int TailIndex = findFirstDataEnd(); //查找报尾的位置  
  76.   
  77.             if (TailIndex == -1)  
  78.             {  
  79.                 return 0;  
  80.             }  
  81.             else if (TailIndex + 4 != length) //包尾与包长度不匹配  
  82.             {  
  83.                 //退出前移除当前报头  
  84.                 m_buffer.RemoveRange(0, 2);  
  85.   
  86.                 return 0;  
  87.             }  
  88.   
  89.             return length;  
  90.         }  
  91.   
  92.         /// <summary>  
  93.         /// 包长度  
  94.         /// </summary>  
  95.         /// <returns></returns>  
  96.         public int GetLength()  
  97.         {  
  98.             //报文起始符 功能码 密码 正文长度 报文终止符 CRC校验码 这六个基础结构占14字节  
  99.             //因此报文长度至少为14  
  100.   
  101.             if (m_buffer.Count >= 14)  
  102.             {  
  103.                 int length = m_buffer[8] * 256 + m_buffer[9];//正文长度  
  104.                 return length + 14;  
  105.             }  
  106.             return 0;  
  107.         }  
  108.   
  109.         /// <summary>  
  110.         /// 提取数据  
  111.         /// </summary>  
  112.         public void Dequeue(byte[] buffer, int offset, int size)  
  113.         {  
  114.             m_buffer.CopyTo(0, buffer, offset, size);  
  115.             m_buffer.RemoveRange(offset, size);  
  116.         }  
  117.   
  118.         /// <summary>  
  119.         /// 队列数据  
  120.         /// </summary>  
  121.         /// <param name="buffer"></param>  
  122.         public void Enqueue(byte[] buffer)  
  123.         {  
  124.             m_buffer.AddRange(buffer);  
  125.         }  
  126.   
  127.   
  128.     }  


调用示例:

[csharp]  view plain  copy
 print ?
  1. private void receive()  
  2.         {  
  3.             while (true)//循环直至用户主动终止线程  
  4.             {  
  5.                 int len = Server.Available;  
  6.                 if (len > 0)  
  7.                 {  
  8.                     byte[] temp = new byte[len];  
  9.                     Server.Receive(temp,len,SocketFlags.None);  
  10.                     buffer.Enqueue(temp);  
  11.                     while (buffer.Find()!=0) //while可处理同时接收到多个包的情况    
  12.                     {  
  13.                         int length = buffer.GetLength();  
  14.                         byte[] readBuffer = new byte[len];  
  15.                         buffer.Dequeue(readBuffer, 0, length);  
  16.                         //OnReceiveDataEx(readBuffer); //这里自己写一个委托或方法就OK了,封装收到一个完整数据包后的工作   
  17.                         //示例,这里简单实用静态属性处理:  
  18.                         DataPacketEx da = Statute.UnPackMessage(readBuffer);  
  19.                         ComFun.receiveList.Add(da);  
  20.                     }  
  21.   
  22.                 }  
  23.   
  24.                 Thread.Sleep(100);//这里需要根据实际的数据吞吐量合理选定线程挂起时间  
  25.             }  
  26.         }  
 其中DataPacketEx是封装数据包正文部分的类,其中的属性记录了要发送的数据
使用时只需开启一个线程,不断的将收到的字节流数据加入缓冲区中。调用Find()方法找寻下一个数据包,如果该方法返回0,说明当前缓冲区中不存在数据包(数据尚未完整接收/存在错误数据,该方法可自行进行处理),如果返回一个正数n,则当前缓冲区中索引0-(n-1)的数据即为一个收到的完整的数据包。对其进行处理即可。


协议的实现

在实现协议前,首先我在自定义的TransCoding类中实现了几个静态方法用于Hex、BCD、string等之间的转换。

[csharp]  view plain  copy
 print ?
  1. /// <summary>  
  2.         /// 将十进制形式字符串转换为BCD码的形式  
  3.         /// </summary>  
  4.         /// <param name="str">十进制形式的待转码字符串,每个字符需为0~9的十进制数字</param>  
  5.         /// <returns></returns>  
  6.         public static byte[] BCDStrToByte(string str)  
  7.         {  
  8.             #region 原方法  
  9.   
  10.             //长度为奇数,队首补0  
  11.             if (str.Length % 2 != 0)  
  12.             {  
  13.                 str = '0' + str;  
  14.             }  
  15.   
  16.             byte[] bcd = new byte[str.Length / 2];  
  17.   
  18.             for (int i = 0; i < str.Length / 2; i++)  
  19.             {  
  20.                 int index = i * 2;  
  21.   
  22.                 //计算BCD[index]处的字节  
  23.                 byte high = (byte)(str[index] - 48);  //高四位  
  24.                 high = (byte)(high << 4);  
  25.                 byte low = (byte)(str[index + 1] - 48); //低四位  
  26.   
  27.                 bcd[i] = (byte)(high | low);  
  28.             }  
  29.   
  30.             return bcd;  
  31.  
  32.             #endregion  
  33.   
  34.         }  
  35.   
  36.         /// <summary>  
  37.         /// 将字节数据转化为16进制的字符串(注意:同样适用与转8421格式的BCD码!!!!)  
  38.         /// </summary>  
  39.         /// <param name="hex"></param>  
  40.         /// <param name="index"></param>  
  41.         /// <returns></returns>  
  42.         public static string ByteToHexStr(byte[] hex, int index)  
  43.         {  
  44.             string hexStr = "";  
  45.             if (index >= hex.Length || index < 0)  
  46.                 throw new Exception("索引超出界限");  
  47.             for (int i = index; i < hex.Length; i++)  
  48.             {  
  49.                 if (Convert.ToInt16(hex[i]) >= 16)  
  50.                 {  
  51.                     hexStr += Convert.ToString(hex[i], 16).ToUpper();  
  52.                 }  
  53.                 else  
  54.                 {  
  55.                     hexStr += "0" + Convert.ToString(hex[i], 16).ToUpper();  
  56.                 }  
  57.             }  
  58.             return hexStr;  
  59.         }  
  60.   
  61.         /// <summary>  
  62.         /// 将16进制字符串转化为字节数据  
  63.         /// </summary>  
  64.         /// <param name="hexStr"></param>  
  65.         /// <returns></returns>  
  66.         public static byte[] HexStrToByte(string hexStr)  
  67.         {  
  68.             if (hexStr.Trim().Length % 2 != 0)  
  69.             {  
  70.                 hexStr = "0" + hexStr;  
  71.             }  
  72.             byte[] hexByte = new byte[hexStr.Length / 2];  
  73.             for (int i = 0; i < hexByte.Length; i++)  
  74.             {  
  75.                 string hex = hexStr[i * 2].ToString(CultureInfo.InvariantCulture) + hexStr[i * 2 + 1].ToString(CultureInfo.InvariantCulture);  
  76.                 hexByte[i] = byte.Parse(hex, NumberStyles.AllowHexSpecifier);  
  77.             }  
  78.             return hexByte;  
  79.  
  80.             #region 使用Convert.ToByte转换  
  81.             //长度为奇数,队首补0,确保整数  
  82.             //if (str.Length % 2 != 0)  
  83.             //{  
  84.             //    str = '0' + str;  
  85.             //}  
  86.   
  87.             //string temp = "";  
  88.             //byte[] BCD = new byte[str.Length / 2];  
  89.   
  90.             //for (int index = 0; index < str.Length; index += 2)  
  91.             //{  
  92.             //    temp = str.Substring(index, 2);  
  93.             //    BCD[index / 2] = Convert.ToByte(temp, 16);  
  94.             //}  
  95.   
  96.             //return BCD;  
  97.             #endregion  
  98.         }  

以下是协议的实现的两个核心方法,装包和解包

装包方法将已有的具体的不同数据类型的数据转换成byte字节流,以便进行socket通信

解包方法将socket接收到的完整数据包字节流解析成封装数据包的类DataPacketEx

[csharp]  view plain  copy
 print ?
  1. /// <summary>  
  2.         ///  构造向终端发送的消息(示例)  
  3.         /// </summary>  
  4.         /// <param name="data">记录发送消息内容的数据包</param>  
  5.         /// <returns>发送的消息</returns>  
  6.         public byte[] BuildMessage(DataPacketEx data)  
  7.         {  
  8.             List<byte> msg = new List<byte>(); //先用消息链表,提高效率  
  9.   
  10.             //帧起始符  
  11.             byte[] tempS = TransCoding.HexStrToByte("FFFF");  
  12.             ComFun.bytePaste(msg, tempS);  
  13.               
  14.             //功能码  
  15.             tempS = TransCoding.HexStrToByte("D1D1");  
  16.             ComFun.bytePaste(msg, tempS);  
  17.   
  18.             //密码  
  19.             tempS = TransCoding.BCDStrToByte("00000001");  
  20.             ComFun.bytePaste(msg, tempS);  
  21.   
  22.             //长度  
  23.             tempS = TransCoding.BCDStrToByte("0006");  
  24.             ComFun.bytePaste(msg, tempS);  
  25.   
  26.             //开关设备编号标识符  
  27.             tempS = TransCoding.HexStrToByte("A001");  
  28.             ComFun.bytePaste(msg, tempS);  
  29.   
  30.             //开关设备编号  
  31.             tempS = TransCoding.BCDStrToByte(data.ObjectID);  
  32.             ComFun.bytePaste(msg, tempS);  
  33.   
  34.             //开/关标识符  
  35.             tempS = TransCoding.HexStrToByte("A002");  
  36.             ComFun.bytePaste(msg, tempS);  
  37.   
  38.             //开/关  
  39.             tempS = TransCoding.BCDStrToByte(data.IsOpen);  
  40.             ComFun.bytePaste(msg, tempS);  
  41.   
  42.             //报文终止符  
  43.             tempS = TransCoding.HexStrToByte("EEEE");  
  44.             ComFun.bytePaste(msg, tempS);  
  45.               
  46.             //CRC校验  
  47.             byte[] message = new byte[msg.Count];  
  48.             for (int i = 0; i < msg.Count; i++)  
  49.             {  
  50.                 message[i] = msg[i];  
  51.             }  
  52.             byte[] crc = new byte[2];  
  53.             Checksum.CalculateCrc16(message, out crc[0], out crc[1]);  
  54.   
  55.             message = new byte[msg.Count + 2];  
  56.             for (int i = 0; i < msg.Count; i++)  
  57.             {  
  58.                 message[i] = msg[i];  
  59.             }  
  60.             message[message.Length - 2] = crc[0];  
  61.             message[message.Length - 1] = crc[1];  
  62.   
  63.             return message;  
  64.   
  65.         }  
  66.   
  67.   
  68.         /// <summary>  
  69.         /// 解包数据  
  70.         /// </summary>  
  71.         /// <param name="message">需要解包的数据</param>  
  72.         /// <returns>成功解析返回true,否则返回false </returns>  
  73.         public DataPacketEx UnPackMessage(byte[] message)  
  74.         {  
  75.             //先校验信息是否传输正确  
  76.             if (!CheckRespose(message))  
  77.                 return null;  
  78.   
  79.             //检查密码是否正确.(假设当前密码为00 00 00 01,需在应用时根据实际情况解决)  
  80.             byte[] temp = new byte[4];  
  81.             temp[0] = message[4];  
  82.             temp[1] = message[5];  
  83.             temp[2] = message[6];  
  84.             temp[3] = message[7];  
  85.             if (TransCoding.ByteToHexStr(temp, 0) != "00000001")  
  86.                 return null;  
  87.   
  88.             DataPacketEx DataPacket = new DataPacketEx("""""");  
  89.   
  90.             //获取功能码  
  91.             byte[] funType = new byte[2] { message[2], message[3] };  
  92.             string functionStr = TransCoding.ByteToHexStr(funType, 0);  
  93.  
  94.             #region 具体解包过程,需根据实际情况修改  
  95.   
  96.             int index = 10; //(当前索引指向第一个标识符)  
  97.             string tempStr="";  
  98.   
  99.             switch (functionStr)  
  100.             {  
  101.                 case "D1D1":  
  102.                     temp = new byte[2] { message[index], message[index + 1] };  
  103.                     index = index + 2;  
  104.                     tempStr = TransCoding.ByteToHexStr(temp, 0);  
  105.                     while (tempStr != "EEEE")  
  106.                     {  
  107.                         switch (tempStr)  
  108.                         {  
  109.                             //注意:每种标识符对应的数据长度是协议中自定义的  
  110.                             case "A001":  
  111.                                 //开关设备编号  
  112.                                 temp = new byte[1] { message[index] };  
  113.                                 index = index + 1;  
  114.                                 tempStr = TransCoding.ByteToHexStr(temp, 0);  
  115.                                 DataPacket.ObjectID = tempStr;  
  116.                                 break;  
  117.                             case "A002":  
  118.                                 //开or关(开:00 关:11)  
  119.                                 temp = new byte[1] { message[index] };  
  120.                                 index = index + 1;  
  121.                                 tempStr = TransCoding.ByteToHexStr(temp, 0);  
  122.                                 DataPacket.IsOpen = tempStr;  
  123.                                 break;  
  124.                             //case "其他标识符":  
  125.                             //    //对应信息  
  126.                             //    break;  
  127.                         }  
  128.                         temp = new byte[2] { message[index], message[index + 1] };  
  129.                         index = index + 2;  
  130.                         tempStr = TransCoding.ByteToHexStr(temp, 0);  
  131.                     }  
  132.                     break;  
  133.                   
  134.                 //case "其他功能码":  
  135.                 //    //对应功能  
  136.                 //    break;  
  137.             }  
  138.  
  139.             #endregion  
  140.   
  141.             return DataPacket;  
  142.         }  

对于通信可靠性的验证

对此,我制作了两个简单的demo,一个服务器端,一个客户端。

客户端可想服务器端循环发送数据,其中以0.5的概率夹杂着随机长度随机取值的干扰数据,以此来判断本协议在实际应用中的可行性。

服务器端负责循环接收并处理显示收到的数据

最终的运行结果如下图:



由运行结果可以看出,服务器端完美屏蔽掉了客户端发出的错误数据,全部解析出了客户端发送的实际数据。证明本协议可以解决类似粘包,传错等等类似的通讯中的棘手问题。当然,协议中如果有不完美的地方,希望各位大神指教。另外,上面的demo只是为了验证协议所做,还存在一些零零碎碎的小bug。

亲测以上代码可以正常使用,下面的连接是作者提供的:http://download.csdn.net/detail/u011583927/8653701 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值