大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > C#技巧 > c# socket通信较完善方案

c# socket通信较完善方案

关键词:c#socket  阅读(810) 赞(10)

[摘要]本文是对c# socket通信较完善方案的讲解,对学习C#编程技术有所帮助,与大家分享。
c#的socket通信应用.文件较多.附件为工程.
core
AbstractBytesWorker.cs 字节工作器(基类),用于用于同一不同功能的字节工作器
BinaryHand.cs 2进制处理器. ThDispose.cs 处理回收相关
crc
entity
ThPersonInfo.cs
manager
ThSocketManager.cs ThSocketManagerBusiness.cs
所有的业务
request
RequestCode.cs 请求码
ThProtocolReq.cs 请求逻辑
ThReqBytesWorker.cs 请求相关的字节工作器
response
respLogic
ThProtocolResp.cs 处理服务器响应的数据.
ThProtocolRespDelegates.cs 所有的代理.用于通知客户的事件.
ThProtocolRespEvents.cs 所有的事件.用于调用客户的.
ThProtocolRespListeners.cs 所有的监听器,用于控制事件如何订阅
ThProtocolRespLogic.cs 处理服务器的数据
ThRespBytesWorker.cs 响应字节处理器
BinaryMessageHandler.cs 处理数据包粘结,包一次数据不足等情况.
ResponseCode.cs 响应码
socket
TAsyncTcpClient.cs tcpClient类,read异步.
testcase
===============================================================
部分类代码: BinaryMessageHandler
C#代码 收藏代码
  1. #pragmawarningdisable0219
  2. usingSystem;
  3. usingSystem.Collections.Generic;
  4. usingSystem.Linq;
  5. usingSystem.Text;
  6. usingSystem.IO;
  7. ///<summary>
  8. ///字节接收处理,粘包问题
  9. ///</summary>
  10. classBinaryMessageHandler:ThDispose
  11. {
  12. List<byte>bytesList=newList<byte>();
  13. privateTAsyncTcpClienttcpClient;
  14. publicBinaryMessageHandler(TAsyncTcpClienttcpClient)
  15. {
  16. this.tcpClient=tcpClient;
  17. }
  18. publicBinaryMessageHandler()
  19. {
  20. }
  21. overridepublicvoidSelfDispose()
  22. {
  23. tcpClient=null;
  24. bytesList=null;
  25. }
  26. ///<summary>
  27. ///累积字节.
  28. ///每次累积后,测试是否有完整的包.
  29. ///</summary>
  30. ///<paramname="buf"></param>
  31. publicvoidWrite(byte[]buf)
  32. {
  33. if(buf.Length>0)
  34. {
  35. //累积字节
  36. bytesList.AddRange(buf);
  37. byte[]bytes=bytesList.ToArray<byte>();
  38. MemoryStreamms=newMemoryStream(bytes);
  39. BinaryReaderreader=newBinaryReader(ms);
  40. intheader=reader.ReadUInt16();
  41. if(header==ThSocketManager.TH_HEADER)
  42. {
  43. intlen=reader.ReadUInt16();
  44. intremainLen=len-4;
  45. if((ms.Length-ms.Position)>=remainLen)
  46. {
  47. //有完整的数据包
  48. ms.Position=0;
  49. byte[]pack=reader.ReadBytes(len);
  50. ReadPackage(pack);
  51. //移除读完的数据包
  52. bytesList.RemoveRange(0,len);
  53. }
  54. }
  55. reader.Close();
  56. ms.Close();
  57. }
  58. }
  59. ///<summary>
  60. ///读取服务端响应信息.
  61. ///</summary>
  62. ///<paramname="bytes"></param>
  63. ///<returns></returns>
  64. publicvoidReadPackage(byte[]bytes)
  65. {
  66. //处理包头
  67. MemoryStreamms=newMemoryStream(bytes);
  68. ms.Position=0;
  69. BinaryReaderreader=newBinaryReader(ms,Encoding.UTF8);
  70. ushortheader=reader.ReadUInt16();
  71. ushorttotalLen=reader.ReadUInt16();
  72. ushortrespCode=reader.ReadUInt16();
  73. shortsignature=reader.ReadInt16();
  74. intdataLen=totalLen-ThSocketManager.PREFIX_LENGTH;
  75. byte[]dataBytes=reader.ReadBytes(dataLen);
  76. reader.Close();
  77. ms.Close();
  78. //调用服务端响应,包体处理器.
  79. tcpClient.thProtocolResp.ResponseHandler(respCode,dataBytes);
  80. }
  81. }
BinaryHand
C#代码 收藏代码
  1. #pragmawarningdisable0219
  2. usingSystem.Text;
  3. usingSystem.IO;
  4. classBinaryHand
  5. {
  6. ///<summary>
  7. ///准备将数据发送至服务端
  8. ///</summary>
  9. ///<paramname="clientId"></param>
  10. ///<paramname="data"></param>
  11. ///<returns></returns>
  12. publicstaticbyte[]ToBytes(ushortrequestCode,uintclientId,byte[]dataBytes)
  13. {
  14. MemoryStreamms=newMemoryStream();
  15. BinaryWriterwriter=newBinaryWriter(ms);
  16. //2ushortheader
  17. writer.Write(ThSocketManager.TH_HEADER);
  18. //2ushorttotallength
  19. ushortpackageLen=ThSocketManager.PREFIX_LENGTH;
  20. if(dataBytes!=null)
  21. {
  22. packageLen+=(ushort)dataBytes.Length;
  23. }
  24. writer.Write(packageLen);
  25. //2ushortprotocolid
  26. writer.Write(requestCode);
  27. //2shortsignature
  28. writer.Write((short)0);
  29. //4unitclientid
  30. //writer.Write(clientId);
  31. //xstringdata
  32. if(dataBytes!=null)
  33. writer.Write(dataBytes);
  34. //计算crc,并写入[6,7]位置.
  35. byte[]tmpBytes=ms.ToArray();
  36. shortsignature=CRC16.Compute(tmpBytes);
  37. longoldPos=ms.Position;
  38. ms.Position=6;
  39. writer.Write(signature);
  40. ms.Position=oldPos;
  41. //准备输出
  42. byte[]bytes=ms.ToArray();
  43. writer.Close();
  44. ms.Close();
  45. returnbytes;
  46. }
  47. publicstaticbyte[]ToBytes(RequestCoderequestCode,uintclientId,byte[]dataBytes)
  48. {
  49. returnToBytes((ushort)requestCode,clientId,dataBytes);
  50. }
  51. publicbyte[]ToBytes(uintclientId,stringdata)
  52. {
  53. byte[]dataBytes=Encoding.UTF8.GetBytes(data);
  54. returnToBytes(RequestCode.None,clientId,dataBytes);
  55. }
  56. ///<summary>
  57. ///读取服务端响应信息.
  58. ///</summary>
  59. ///<paramname="bytes"></param>
  60. ///<returns></returns>
  61. publicbyte[]FromBytes(byte[]bytes)
  62. {
  63. MemoryStreamms=newMemoryStream(bytes);
  64. ms.Position=0;
  65. BinaryReaderreader=newBinaryReader(ms,Encoding.UTF8);
  66. ushortheader=reader.ReadUInt16();
  67. ushorttotalLen=reader.ReadUInt16();
  68. ushortprotocolId=reader.ReadUInt16();
  69. shortsignature=reader.ReadInt16();
  70. uintclientId=reader.ReadUInt32();
  71. intdataLen=totalLen-ThSocketManager.PREFIX_LENGTH;
  72. byte[]dataBytes=reader.ReadBytes(dataLen);
  73. reader.Close();
  74. ms.Close();
  75. returndataBytes;
  76. }
  77. }
  • cusCom.rar(124.7 KB)


相关评论