c# socket通信较完善方案1

[b]c#的socket通信应用.文件较多.附件为工程.
[/b]
[i]core[/i]
AbstractBytesWorker.cs 字节工作器(基类),用于用于同一不同功能的字节工作器
BinaryHand.cs 2进制处理器.
ThDispose.cs 处理回收相关
[u]crc [/u]

[u]entity[/u]
ThPersonInfo.cs
[u]manager[/u]
ThSocketManager.cs
ThSocketManagerBusiness.cs 所有的业务
[u]request[/u]
RequestCode.cs 请求码
ThProtocolReq.cs 请求逻辑
ThReqBytesWorker.cs 请求相关的字节工作器
[u]response[/u]
[u] respLogic[/u]
ThProtocolResp.cs 处理服务器响应的数据.
ThProtocolRespDelegates.cs 所有的代理.用于通知客户的事件.
ThProtocolRespEvents.cs 所有的事件.用于调用客户的.
ThProtocolRespListeners.cs 所有的监听器,用于控制事件如何订阅
ThProtocolRespLogic.cs 处理服务器的数据
ThRespBytesWorker.cs 响应字节处理器
BinaryMessageHandler.cs 处理数据包粘结,包一次数据不足等情况.
ResponseCode.cs 响应码
[u]socket[/u]
TAsyncTcpClient.cs tcpClient类,read异步.
[u]testcase[/u]
===============================================================
部分类代码:
BinaryMessageHandler

#pragma warning disable 0219
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

/// <summary>
/// 字节接收处理,粘包问题
/// </summary>
class BinaryMessageHandler : ThDispose
{
List<byte> bytesList = new List<byte>();

private TAsyncTcpClient tcpClient;

public BinaryMessageHandler(TAsyncTcpClient tcpClient)
{
this.tcpClient = tcpClient;
}
public BinaryMessageHandler()
{

}

override public void SelfDispose()
{
tcpClient = null;
bytesList = null;
}

/// <summary>
/// 累积 字节.
/// 每次累积后,测试是否有完整的包.
/// </summary>
/// <param name="buf"></param>
public void Write(byte[] buf)
{
if (buf.Length > 0)
{
//累积字节
bytesList.AddRange(buf);
byte[] bytes = bytesList.ToArray<byte>();
MemoryStream ms = new MemoryStream(bytes);
BinaryReader reader = new BinaryReader(ms);

int header = reader.ReadUInt16();
if (header == ThSocketManager.TH_HEADER)
{
int len = reader.ReadUInt16();
int remainLen = len - 4;
if ((ms.Length - ms.Position) >= remainLen)
{
//有完整的数据包
ms.Position = 0;
byte[] pack = reader.ReadBytes(len);

ReadPackage(pack);
//移除读完的数据包
bytesList.RemoveRange(0, len);
}
}
reader.Close();
ms.Close();
}

}

/// <summary>
/// 读取服务端响应信息.
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public void ReadPackage(byte[] bytes)
{
//处理包头
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
BinaryReader reader = new BinaryReader(ms, Encoding.UTF8);
ushort header = reader.ReadUInt16();
ushort totalLen = reader.ReadUInt16();
ushort respCode = reader.ReadUInt16();
short signature = reader.ReadInt16();
int dataLen = totalLen - ThSocketManager.PREFIX_LENGTH;
byte[] dataBytes = reader.ReadBytes(dataLen);
reader.Close();
ms.Close();

//调用服务端响应,包体处理器.
tcpClient.thProtocolResp.ResponseHandler(respCode, dataBytes);
}
}


BinaryHand

#pragma warning disable 0219
using System.Text;
using System.IO;

class BinaryHand
{
/// <summary>
/// 准备将数据发送至服务端
/// </summary>
/// <param name="clientId"></param>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] ToBytes(ushort requestCode, uint clientId, byte[] dataBytes)
{
MemoryStream ms = new MemoryStream();
BinaryWriter writer = new BinaryWriter(ms);
//2 ushort header
writer.Write(ThSocketManager.TH_HEADER);
//2 ushort total length
ushort packageLen = ThSocketManager.PREFIX_LENGTH;
if (dataBytes != null)
{
packageLen += (ushort)dataBytes.Length;
}
writer.Write(packageLen);
//2 ushort protocol id
writer.Write(requestCode);
//2 short signature
writer.Write((short)0);
//4 unit client id
//writer.Write(clientId);
//x string data
if (dataBytes != null)
writer.Write(dataBytes);
//计算crc,并写入[6,7]位置.
byte[] tmpBytes = ms.ToArray();
short signature = CRC16.Compute(tmpBytes);
long oldPos = ms.Position;
ms.Position = 6;
writer.Write(signature);
ms.Position = oldPos;
//准备输出
byte[] bytes = ms.ToArray();

writer.Close();
ms.Close();
return bytes;
}

public static byte[] ToBytes(RequestCode requestCode, uint clientId, byte[] dataBytes)
{
return ToBytes((ushort)requestCode, clientId, dataBytes);
}

public byte[] ToBytes(uint clientId, string data)
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
return ToBytes(RequestCode.None, clientId, dataBytes);
}

/// <summary>
/// 读取服务端响应信息.
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public byte[] FromBytes(byte[] bytes)
{
MemoryStream ms = new MemoryStream(bytes);
ms.Position = 0;
BinaryReader reader = new BinaryReader(ms, Encoding.UTF8);
ushort header = reader.ReadUInt16();
ushort totalLen = reader.ReadUInt16();
ushort protocolId = reader.ReadUInt16();
short signature = reader.ReadInt16();
uint clientId = reader.ReadUInt32();
int dataLen = totalLen - ThSocketManager.PREFIX_LENGTH;
byte[] dataBytes = reader.ReadBytes(dataLen);

reader.Close();
ms.Close();
return dataBytes;
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gamebox1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值