zoukankan      html  css  js  c++  java
  • c# socket通信较完善方案

    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. #pragma warning disable 0219  
    2. using System;  
    3. using System.Collections.Generic;  
    4. using System.Linq;  
    5. using System.Text;  
    6. using System.IO;  
    7.   
    8. /// <summary>  
    9. /// 字节接收处理,粘包问题  
    10. /// </summary>  
    11. class BinaryMessageHandler : ThDispose  
    12. {  
    13.     List<byte> bytesList = new List<byte>();  
    14.   
    15.     private TAsyncTcpClient tcpClient;  
    16.   
    17.     public BinaryMessageHandler(TAsyncTcpClient tcpClient)  
    18.     {  
    19.         this.tcpClient = tcpClient;  
    20.     }  
    21.     public BinaryMessageHandler()  
    22.     {  
    23.   
    24.     }  
    25.   
    26.     override public void SelfDispose()  
    27.     {  
    28.         tcpClient = null;  
    29.         bytesList = null;  
    30.     }  
    31.       
    32.     /// <summary>  
    33.     /// 累积 字节.  
    34.     /// 每次累积后,测试是否有完整的包.  
    35.     /// </summary>  
    36.     /// <param name="buf"></param>  
    37.     public void Write(byte[] buf)  
    38.     {  
    39.         if (buf.Length > 0)  
    40.         {  
    41.             //累积字节  
    42.             bytesList.AddRange(buf);  
    43.             byte[] bytes = bytesList.ToArray<byte>();  
    44.             MemoryStream ms = new MemoryStream(bytes);  
    45.             BinaryReader reader = new BinaryReader(ms);  
    46.   
    47.             int header = reader.ReadUInt16();  
    48.             if (header == ThSocketManager.TH_HEADER)  
    49.             {  
    50.                 int len = reader.ReadUInt16();  
    51.                 int remainLen = len - 4;  
    52.                 if ((ms.Length - ms.Position) >= remainLen)  
    53.                 {  
    54.                     //有完整的数据包  
    55.                     ms.Position = 0;  
    56.                     byte[] pack = reader.ReadBytes(len);  
    57.   
    58.                     ReadPackage(pack);  
    59.                     //移除读完的数据包  
    60.                     bytesList.RemoveRange(0, len);  
    61.                 }  
    62.             }  
    63.             reader.Close();  
    64.             ms.Close();  
    65.         }  
    66.   
    67.     }  
    68.   
    69.     /// <summary>  
    70.     /// 读取服务端响应信息.  
    71.     /// </summary>  
    72.     /// <param name="bytes"></param>  
    73.     /// <returns></returns>  
    74.     public void ReadPackage(byte[] bytes)  
    75.     {  
    76.         //处理包头  
    77.         MemoryStream ms = new MemoryStream(bytes);  
    78.         ms.Position = 0;  
    79.         BinaryReader reader = new BinaryReader(ms, Encoding.UTF8);  
    80.         ushort header = reader.ReadUInt16();  
    81.         ushort totalLen = reader.ReadUInt16();  
    82.         ushort respCode = reader.ReadUInt16();  
    83.         short signature = reader.ReadInt16();  
    84.         int dataLen = totalLen - ThSocketManager.PREFIX_LENGTH;  
    85.         byte[] dataBytes = reader.ReadBytes(dataLen);  
    86.         reader.Close();  
    87.         ms.Close();  
    88.   
    89.         //调用服务端响应,包体处理器.  
    90.         tcpClient.thProtocolResp.ResponseHandler(respCode, dataBytes);  
    91.     }  
    92. }  
    BinaryHand 
    C#代码  收藏代码
    1. #pragma warning disable 0219  
    2. using System.Text;  
    3. using System.IO;  
    4.   
    5. class BinaryHand  
    6. {  
    7.     /// <summary>  
    8.     /// 准备将数据发送至服务端  
    9.     /// </summary>  
    10.     /// <param name="clientId"></param>  
    11.     /// <param name="data"></param>  
    12.     /// <returns></returns>  
    13.     public static byte[] ToBytes(ushort requestCode, uint clientId, byte[] dataBytes)  
    14.     {  
    15.         MemoryStream ms = new MemoryStream();  
    16.         BinaryWriter writer = new BinaryWriter(ms);  
    17.         //2 ushort header  
    18.         writer.Write(ThSocketManager.TH_HEADER);  
    19.         //2 ushort total length  
    20.         ushort packageLen = ThSocketManager.PREFIX_LENGTH;  
    21.         if (dataBytes != null)  
    22.         {  
    23.             packageLen += (ushort)dataBytes.Length;  
    24.         }  
    25.         writer.Write(packageLen);  
    26.         //2 ushort protocol id  
    27.         writer.Write(requestCode);  
    28.         //2 short signature  
    29.         writer.Write((short)0);  
    30.         //4 unit client id  
    31.         //writer.Write(clientId);  
    32.         //x string data  
    33.         if (dataBytes != null)  
    34.             writer.Write(dataBytes);  
    35.         //计算crc,并写入[6,7]位置.  
    36.         byte[] tmpBytes = ms.ToArray();  
    37.         short signature = CRC16.Compute(tmpBytes);  
    38.         long oldPos = ms.Position;  
    39.         ms.Position = 6;  
    40.         writer.Write(signature);  
    41.         ms.Position = oldPos;  
    42.         //准备输出  
    43.         byte[] bytes = ms.ToArray();  
    44.   
    45.         writer.Close();  
    46.         ms.Close();  
    47.         return bytes;  
    48.     }  
    49.   
    50.     public static byte[] ToBytes(RequestCode requestCode, uint clientId, byte[] dataBytes)  
    51.     {  
    52.         return ToBytes((ushort)requestCode, clientId, dataBytes);  
    53.     }  
    54.   
    55.     public byte[] ToBytes(uint clientId, string data)  
    56.     {  
    57.         byte[] dataBytes = Encoding.UTF8.GetBytes(data);  
    58.         return ToBytes(RequestCode.None, clientId, dataBytes);  
    59.     }  
    60.   
    61.     /// <summary>  
    62.     /// 读取服务端响应信息.  
    63.     /// </summary>  
    64.     /// <param name="bytes"></param>  
    65.     /// <returns></returns>  
    66.     public byte[] FromBytes(byte[] bytes)  
    67.     {  
    68.         MemoryStream ms = new MemoryStream(bytes);  
    69.         ms.Position = 0;  
    70.         BinaryReader reader = new BinaryReader(ms, Encoding.UTF8);  
    71.         ushort header = reader.ReadUInt16();  
    72.         ushort totalLen = reader.ReadUInt16();  
    73.         ushort protocolId = reader.ReadUInt16();  
    74.         short signature = reader.ReadInt16();  
    75.         uint clientId = reader.ReadUInt32();  
    76.         int dataLen = totalLen - ThSocketManager.PREFIX_LENGTH;  
    77.         byte[] dataBytes = reader.ReadBytes(dataLen);  
    78.   
    79.         reader.Close();  
    80.         ms.Close();  
    81.         return dataBytes;  
    82.     }  
    83. }  
  • 相关阅读:
    为Fiddler增加Burp-like Inspector扩展 实现类似Burpsuite爆破、一键重放、编码转换等功能
    SVN常见问题总结一
    手把手教你学SVN
    js基本语法汇总
    最全的常用正则表达式大全
    CSS padding margin border属性详解
    从零开始学习jQuery (五) 事件与事件对象
    js正则表达式语法
    浏览器内部工作原理
    原生AJAX入门讲解(含实例)
  • 原文地址:https://www.cnblogs.com/gc2013/p/3853375.html
Copyright © 2011-2022 走看看