首页 > 学院 > 开发设计 > 正文

c# socket通信较完善方案

2019-11-17 03:01:54
字体:
来源:转载
供稿:网友
c# socket通信较完善方案c#的socket通信应用.文件较多.附件为工程. core AbstractBytesWorker.cs 字节工作器(基类),用于用于同一不同功能的字节工作器 BinaryHand.cs 2进制处理器. ThDispose.cs 处理回收相关 crcentity 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 =============================================================== 部分类代码: BinaryMessageHandlerC#代码收藏代码
  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"><
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表