浅谈C#之TuochSocket
一、基本介绍
TouchSocket 是一个为 .Net(包括 C#、VB.Net、F#)设计的整合性、超轻量级的网络通信框架,它包含了 tcp、udp、ssl、http、websocket、rpc、jsonrpc、webapi、xmlrpc 等一系列的通信模块。它能够一键式解决 TCP 黏分包问题,udp 大数据包分片组合问题等,使用协议模板可以快速实现「固定包头」、「固定长度」、「区间字符」等一系列的数据报文解析。
二、基本示例
以下是使用 TouchSocket 实现 Tcp 协议通讯,并解决分包、粘包问题的基本示例:
客户端代码示例:
TouchSocket.Sockets.TcpClient tcpClient = new TouchSocket.Sockets.TcpClient();
tcpClient.Connecting = (client, e) =>
{// 这里是指增加Int大小的包头client.SetDataHandlingAdapter(new FixedHeaderPackageAdapter() { FixedHeaderType = FixedHeaderType.Int });
};
tcpClient.Received = (client, byteBlock, obj) =>
{// 前4字节为包头,包含了包大小信息var data = new byte[byteBlock.Buffer.Length - 4];Array.Copy(byteBlock.Buffer, 4, data, 0, data.Length);// 从服务器收到信息string mes = Encoding.UTF8.GetString(data, 0, data.Length);var text = $"已从服务器接收到信息:{mes}\r\n";Console.WriteLine(text);Application.Current.Dispatcher.Invoke(() =>{textBlock.Text += text;});
};
tcpClient.Setup("127.0.0.1:21345");
tcpClient.Connect();
var str = "物服务器服务器服务器发起非亲非故";
var bytes = Encoding.UTF8.GetBytes(str);
var addLen = AddLen(bytes);
tcpClient.Send(addLen);
tcpClient.Close();// 增加包头
internal byte[] AddLen(byte[] bytes)
{int dataLength = bytes.Length;var dataLengthBytes = BitConverter.GetBytes(dataLength);byte[] sendBuffer = new byte[dataLengthBytes.Length + bytes.Length]; // 为数据包申请缓存,包括4个字节的分隔符和实际数据Buffer.BlockCopy(dataLengthBytes, 0, sendBuffer, 0, dataLengthBytes.Length); // 将长度信息写入数据包缓存的前面4个字节Buffer.BlockCopy(bytes, 0, sendBuffer, dataLengthBytes.Length, bytes.Length); // 将实际数据写入数据包缓存的后面return sendBuffer;
}
服务端代码示例:
TcpService service = new TcpService();
service.Connecting = (client, ex) =>
{client.SetDataHandlingAdapter(new FixedHeaderPackageAdapter() { FixedHeaderType = FixedHeaderType.Int });
};
service.Connected += (client, args) =>
{_socketClient = client;
};
service.Received = (client, byteBlock, requestInfo) =>
{var array = byteBlock.ToArray();// 前4字节为包头,包含了包大小信息var data = new byte[byteBlock.Buffer.Length - 4];Array.Copy(byteBlock.Buffer, 4, data, 0, data.Length);var text = $"已从{client.IP}:{client.Port}接收到信息:{Encoding.UTF8.GetString(data)}\r\n";Console.WriteLine(text); //Name即IP+PortApplication.Current.Dispatcher.Invoke(() =>{textBlock.Text += text;});
}