🌐 通信类
概述
Snet 框架提供 12 个通信类,涵盖 TCP、UDP(单播/广播/组播)、WebSocket、HTTP 和串口通信。所有通信类使用嵌套的 Basics 类进行配置。客户端类继承自 CommunicationAbstract(实现 ICommunication 接口)。服务端类继承自 CommunicationServiceAbstract(实现 ICommunicationService 接口)。
快速参考
| 类 | 类型 | 基类 | 关键协议 | 默认端口 |
|---|---|---|---|---|
TcpClientOperate |
客户端 | CommunicationAbstract |
TCP | 6688 |
UdpClientOperate |
客户端 | CommunicationAbstract |
UDP 单播 | 6688 |
UdpBroadcastOperate |
客户端 | CommunicationAbstract |
UDP 广播 | 6688(绑定)/ 8866(发送) |
UdpMulticastOperate |
客户端 | CommunicationAbstract |
UDP 组播 | 6688(绑定)/ 8866(发送) |
WsClientOperate |
客户端 | CommunicationAbstract |
WebSocket | 6688 |
HttpClientOperate |
客户端 | CommunicationAbstract |
HTTP | 不适用 |
SerialOperate |
客户端 | CommunicationAbstract |
串口 | 不适用 |
TcpServiceOperate |
服务端 | CommunicationServiceAbstract |
TCP | 6688 |
UdpServiceOperate |
服务端 | CommunicationServiceAbstract |
UDP 单播 | 6688 |
WsServiceOperate |
服务端 | CommunicationServiceAbstract |
WebSocket | 6688 |
HttpServiceOperate |
服务端 | CommunicationServiceAbstract |
HTTP | 6688 |
WebSocketServer |
服务端 | CommunicationServiceAbstract |
WebSocket | 不适用 |
客户端类
TcpClientOperate
命名空间: Snet.Core.communication.net.tcp.client
数据类: TcpClientData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid.ToUpperNString() |
唯一标识符 |
| IpAddress | string |
"127.0.0.1" |
Ip地址 |
| Port | int |
6688 |
端口 |
| InterruptReconnection | bool |
true |
是否需要断开重新连接 |
| ReconnectionInterval | int |
1000 |
重连间隔(毫秒) |
| Timeout | int |
1000 |
超时时间(毫秒) |
| SendWaitInterval | virtual int |
5000 |
发送等待间隔 |
| MaxChunkSize | virtual int |
255*1024 |
最大块大小 |
| RetrySendCount | virtual int |
5 |
重试发送次数 |
| BufferSize | virtual int |
1024*1024 |
数据缓冲区大小 |
// 创建并连接 TCP 客户端
var tcpClient = new TcpClientOperate("tcp-client-01");
tcpClient.Data.Basics.IpAddress = "192.168.1.100";
tcpClient.Data.Basics.Port = 6688;
tcpClient.Data.Basics.BufferSize = 1024 * 1024;
await tcpClient.ConnectAsync();
// 发送数据
byte[] data = Encoding.UTF8.GetBytes("你好,TCP 服务器!");
var result = await tcpClient.SendAsync(data);
// 接收数据
tcpClient.OnDataReceived += (sender, args) =>
{
string message = Encoding.UTF8.GetString(args.Data);
Console.WriteLine($"收到消息:{message}");
};
UdpClientOperate
命名空间: Snet.Core.communication.net.udp.unicast.client
数据类: UdpClientData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| IpAddress | string |
"127.0.0.1" |
Ip地址 |
| Port | int |
6688 |
端口 |
| LocalPort | int |
0 |
本地端口(0=系统自动分配) |
| InterruptReconnection | bool |
true |
是否需要断开重新连接 |
| ReconnectionInterval | int |
1000 |
重连间隔(毫秒) |
| Timeout | int |
1000 |
超时时间(毫秒) |
| SendWaitInterval | virtual int |
5000 |
发送等待间隔 |
| MaxChunkSize | virtual int |
255*1024 |
最大块大小 |
| RetrySendCount | virtual int |
5 |
重试发送次数 |
// 使用本地端口设置 UDP 客户端
var udpClient = new UdpClientOperate("udp-client-01");
udpClient.Data.Basics.IpAddress = "192.168.1.100";
udpClient.Data.Basics.Port = 6688;
udpClient.Data.Basics.LocalPort = 0; // 系统自动分配本地端口
await udpClient.ConnectAsync();
byte[] data = Encoding.UTF8.GetBytes("UDP 消息");
await udpClient.SendAsync(data);
UdpBroadcastOperate
命名空间: Snet.Core.communication.net.udp.broadcast
数据类: UdpBroadcastData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| Port | int |
6688 |
本地绑定端口(接收数据用) |
| BroadcastAddress | string |
"255.255.255.255" |
广播地址 |
| BroadcastPort | int |
8866 |
广播端口(发送目标端口) |
| Timeout | int |
1000 |
超时时间(毫秒) |
| SendWaitInterval | virtual int |
5000 |
发送等待间隔 |
| MaxChunkSize | virtual int |
255*1024 |
最大块大小 |
| RetrySendCount | virtual int |
5 |
重试发送次数 |
内部逻辑:
EffectiveBroadcastPort解析为BroadcastPort > 0 ? BroadcastPort : Port。
// 使用 UdpBroadcastOperate 进行广播
var broadcast = new UdpBroadcastOperate("udp-broadcast-01");
broadcast.Data.Basics.Port = 6688; // 本地绑定端口
broadcast.Data.Basics.BroadcastPort = 8866; // 目标广播端口
broadcast.Data.Basics.BroadcastAddress = "255.255.255.255";
await broadcast.ConnectAsync();
byte[] broadcastData = Encoding.UTF8.GetBytes("向所有设备广播消息");
await broadcast.SendAsync(broadcastData);
// 监听传入的广播回复
broadcast.OnDataReceived += (sender, args) =>
{
string received = Encoding.UTF8.GetString(args.Data);
Console.WriteLine($"广播回复:{received}");
};
UdpMulticastOperate
命名空间: Snet.Core.communication.net.udp.multicast
数据类: UdpMulticastData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| Port | int |
6688 |
本地绑定端口(接收数据用) |
| MulticastAddress | string |
"239.0.0.1" |
组播组地址 |
| MulticastPort | int |
8866 |
组播端口(发送目标端口) |
| TimeToLive | short |
1 |
生存时间(TTL) |
| Timeout | int |
1000 |
超时时间(毫秒) |
| SendWaitInterval | virtual int |
5000 |
发送等待间隔 |
| MaxChunkSize | virtual int |
255*1024 |
最大块大小 |
| RetrySendCount | virtual int |
5 |
重试发送次数 |
内部逻辑:
EffectiveMulticastPort解析为MulticastPort > 0 ? MulticastPort : Port。
// 使用 UdpMulticastOperate 加入组播组
var multicast = new UdpMulticastOperate("udp-multicast-01");
multicast.Data.Basics.Port = 6688; // 本地绑定端口
multicast.Data.Basics.MulticastAddress = "239.0.0.1";
multicast.Data.Basics.MulticastPort = 8866; // 目标组播端口
multicast.Data.Basics.TimeToLive = 1; // 仅本地子网
await multicast.ConnectAsync();
byte[] multicastData = Encoding.UTF8.GetBytes("组播组消息");
await multicast.SendAsync(multicastData);
// 接收组播数据
multicast.OnDataReceived += (sender, args) =>
{
string message = Encoding.UTF8.GetString(args.Data);
Console.WriteLine($"组播收到:{message}");
};
WsClientOperate
命名空间: Snet.Core.communication.net.ws.client
数据类: WsClientData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| Host | string |
"ws://127.0.0.1:6688/" |
主机地址 |
| InterruptReconnection | bool |
true |
是否需要断开重新连接 |
| ReconnectionInterval | int |
1000 |
重连间隔(毫秒) |
| Timeout | int |
1000 |
超时时间(毫秒) |
| SendWaitInterval | virtual int |
5000 |
发送等待间隔 |
| MaxChunkSize | virtual int |
255*1024 |
最大块大小 |
| RetrySendCount | virtual int |
5 |
重试发送次数 |
| BufferSize | virtual int |
1024*1024 |
数据缓冲区大小 |
// 使用 WsClientOperate 连接 WebSocket
var wsClient = new WsClientOperate("ws-client-01");
wsClient.Data.Basics.Host = "ws://192.168.1.100:6688/";
wsClient.Data.Basics.InterruptReconnection = true;
wsClient.Data.Basics.ReconnectionInterval = 1000;
await wsClient.ConnectAsync();
// 发送数据
byte[] wsData = Encoding.UTF8.GetBytes("WebSocket 消息");
await wsClient.SendAsync(wsData);
// 接收数据
wsClient.OnDataReceived += (sender, args) =>
{
string message = Encoding.UTF8.GetString(args.Data);
Console.WriteLine($"WebSocket 收到:{message}");
};
HttpClientOperate
命名空间: Snet.Core.communication.net.http.client
数据类: HttpClientData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string |
Guid |
唯一标识符 |
| MaxConnectCount | int |
255 |
最大连接数 |
HttpClientData 中的其他嵌套类型:
BType枚举:FormData— 表单形式传输数据(multipart/form-data)Raw— 原始数据形式传输数据(application/json)None— 无内容
RequestData:Url、Headers(Dictionary)、Method(HttpMethod)、BodyType(BType)、BodyContent(object)、Encoding(Encoding)、ContentType(string)、TimeOut(TimeSpan)、Proxy(IWebProxy?)、CookieContainerResponseData:StatusCode(int)、ResHeadersDatas(Dictionary)、ResCookieData(CookieCollection)、ResData(string?)、ReqData(RequestData)
// 使用 HttpClientOperate 发起 HTTP 请求
var httpClient = new HttpClientOperate("http-client-01");
httpClient.Data.Basics.MaxConnectCount = 255;
var request = new HttpClientData.RequestData
{
Url = "https://api.example.com/data",
Method = HttpMethod.Get,
ContentType = "application/json",
TimeOut = TimeSpan.FromSeconds(30)
};
var response = await httpClient.SendAsync(request);
if (response.StatusCode == 200)
{
Console.WriteLine($"响应内容:{response.ResData}");
}
SerialOperate
命名空间: Snet.Core.communication.serial
数据类: SerialData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| PortName | string |
"COM1" |
串口号 |
| BaudRate | int |
19200 |
波特率 |
| ParityBit | Parity |
Even |
校验位 |
| DataBit | int |
8 |
数据位 |
| StopBit | StopBits |
One |
停止位 |
| WriteTimeout | int |
1000 |
写入超时时间 |
| ReadTimeout | int |
1000 |
读取超时时间 |
| ReceivedBytesThreshold | int |
1 |
接收缓冲区中数据的字节数阈值 |
| SendWaitInterval | virtual int |
5000 |
发送等待间隔 |
| MaxChunkSize | virtual int |
255*1024 |
最大块大小 |
| RetrySendCount | virtual int |
5 |
重试发送次数 |
| BufferSize | virtual int |
1024*1024 |
数据缓冲区大小 |
静态方法: string[] GetPortArray() — 获取可用的串口名称列表。
// 使用 SerialOperate 打开串口
var serial = new SerialOperate("serial-01");
serial.Data.Basics.PortName = "COM3";
serial.Data.Basics.BaudRate = 9600;
serial.Data.Basics.ParityBit = Parity.None;
serial.Data.Basics.DataBit = 8;
serial.Data.Basics.StopBit = StopBits.One;
serial.Data.Basics.ReadTimeout = 1000;
serial.Data.Basics.WriteTimeout = 1000;
await serial.ConnectAsync();
// 发送数据
byte[] serialData = Encoding.ASCII.GetBytes("AT\r\n");
await serial.SendAsync(serialData);
// 接收数据
serial.OnDataReceived += (sender, args) =>
{
string response = Encoding.ASCII.GetString(args.Data);
Console.WriteLine($"串口响应:{response}");
};
// 获取可用端口
string[] availablePorts = SerialOperate.GetPortArray();
Console.WriteLine($"可用端口:{string.Join("、", availablePorts)}");
服务端类
TcpServiceOperate
命名空间: Snet.Core.communication.net.tcp.service
数据类: TcpServiceData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| IpAddress | string? |
"127.0.0.1" |
Ip地址 |
| Port | int |
6688 |
端口 |
| MaxNumber | int |
1000 |
最大连接数 |
| MaxChunkSize | int |
255*1024 |
最大块大小 |
| RetrySendCount | int |
5 |
重试发送次数 |
| Timeout | int |
1000 |
超时时间(毫秒) |
| BufferSize | int |
1024*1024 |
数据缓冲区大小 |
其他嵌套类型:
TcpServiceData.ClientMessage:Step、IpPort、BytesTcpServiceData.Steps枚举:客户端连接、客户端断开、消息接收
// 使用 TcpServiceOperate 创建 TCP 服务器
var tcpService = new TcpServiceOperate("tcp-service-01");
tcpService.Data.Basics.IpAddress = "127.0.0.1";
tcpService.Data.Basics.Port = 6688;
tcpService.Data.Basics.MaxNumber = 1000;
tcpService.Data.Basics.BufferSize = 1024 * 1024;
// 处理客户端消息
tcpService.OnClientMessage += (sender, args) =>
{
switch (args.Step)
{
case TcpServiceData.Steps.客户端连接:
Console.WriteLine($"客户端已连接:{args.IpPort}");
break;
case TcpServiceData.Steps.客户端断开:
Console.WriteLine($"客户端已断开:{args.IpPort}");
break;
case TcpServiceData.Steps.消息接收:
string message = Encoding.UTF8.GetString(args.Bytes);
Console.WriteLine($"来自 {args.IpPort} 的消息:{message}");
// 回显消息
tcpService.SendToClientAsync(args.IpPort, args.Bytes);
break;
}
};
await tcpService.StartAsync();
UdpServiceOperate
命名空间: Snet.Core.communication.net.udp.unicast.service
数据类: UdpServiceData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string? |
Guid |
唯一标识符 |
| IpAddress | string? |
"127.0.0.1" |
Ip地址 |
| Port | int |
6688 |
端口 |
| MaxChunkSize | int |
255*1024 |
最大块大小 |
| RetrySendCount | int |
5 |
重试发送次数 |
| Timeout | int |
1000 |
超时时间(毫秒) |
其他嵌套类型:
UdpServiceData.ClientMessage:Step、IpPort、BytesUdpServiceData.Steps枚举:客户端连接、客户端断开、消息接收
// 使用 UdpServiceOperate 创建 UDP 服务器
var udpService = new UdpServiceOperate("udp-service-01");
udpService.Data.Basics.IpAddress = "127.0.0.1";
udpService.Data.Basics.Port = 6688;
udpService.OnClientMessage += (sender, args) =>
{
switch (args.Step)
{
case UdpServiceData.Steps.客户端连接:
Console.WriteLine($"UDP 客户端已注册:{args.IpPort}");
break;
case UdpServiceData.Steps.客户端断开:
Console.WriteLine($"UDP 客户端已移除:{args.IpPort}");
break;
case UdpServiceData.Steps.消息接收:
string message = Encoding.UTF8.GetString(args.Bytes);
Console.WriteLine($"来自 {args.IpPort} 的 UDP 消息:{message}");
break;
}
};
await udpService.StartAsync();
WsServiceOperate
命名空间: Snet.Core.communication.net.ws.service
数据类: WsServiceData.Basics
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string |
Guid |
唯一标识符 |
| Host | string |
"ws://127.0.0.1:6688/" |
地址 |
| MaxChunkSize | int |
255*1024 |
最大块大小 |
| RetrySendCount | int |
5 |
重试发送次数 |
| Timeout | int |
1000 |
超时时间(毫秒) |
| BufferSize | int |
1024*1024 |
数据缓冲区大小 |
其他嵌套类型:
WsServiceData.ClientMessage:Step、IpPort、ClientId、BytesWsServiceData.Steps枚举:客户端连接、客户端断开、消息接收
// 处理 WebSocket 服务中的客户端消息
var wsService = new WsServiceOperate("ws-service-01");
wsService.Data.Basics.Host = "ws://127.0.0.1:6688/";
wsService.Data.Basics.BufferSize = 1024 * 1024;
wsService.OnClientMessage += (sender, args) =>
{
switch (args.Step)
{
case WsServiceData.Steps.客户端连接:
Console.WriteLine($"WebSocket 客户端已连接。ClientId:{args.ClientId},IpPort:{args.IpPort}");
wsService.SendToClientAsync(args.ClientId,
Encoding.UTF8.GetBytes("欢迎连接到 WebSocket 服务器!"));
break;
case WsServiceData.Steps.客户端断开:
Console.WriteLine($"WebSocket 客户端已断开。ClientId:{args.ClientId}");
break;
case WsServiceData.Steps.消息接收:
string message = Encoding.UTF8.GetString(args.Bytes);
Console.WriteLine($"来自 {args.ClientId} 的 WebSocket 消息:{message}");
break;
}
};
await wsService.StartAsync();
HttpServiceOperate
命名空间: Snet.Core.communication.net.http.service
数据类: HttpServiceData.Basics(继承自 WAModel,继承属性 IpAddress="127.0.0.1"、Port=6688、CrossDomain=false)
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| SN | string |
Guid |
唯一标识符 |
| Method | HttpMethod |
Get |
请求与响应的方式 |
| ContentType | string |
"application/json" |
请求与响应的内容类型 |
| AbsolutePaths | List<string> |
["/api/snet"] |
接口的绝对路径集合 |
方法: SET(WAModel) — 快速设置 API 模型参数。
其他嵌套类型:
HttpServiceData.WaitHandler:HttpListenerRequest Request、HttpListenerResponse Response、string? BodyData
// 使用 HttpServiceOperate 设置 HTTP API 服务
var httpService = new HttpServiceOperate("http-service-01");
httpService.Data.Basics.IpAddress = "127.0.0.1";
httpService.Data.Basics.Port = 6688;
httpService.Data.Basics.AbsolutePaths = new List<string> { "/api/snet", "/api/data" };
httpService.Data.Basics.Method = HttpMethod.Post;
httpService.Data.Basics.ContentType = "application/json";
httpService.OnRequest += (sender, handler) =>
{
Console.WriteLine($"请求:{handler.Request.HttpMethod} {handler.Request.Url}");
string responseJson = "{\"status\": \"ok\", \"message\": \"来自 Snet API 的问候\"}";
byte[] buffer = Encoding.UTF8.GetBytes(responseJson);
handler.Response.StatusCode = 200;
handler.Response.ContentType = "application/json";
handler.Response.ContentLength64 = buffer.Length;
handler.Response.OutputStream.Write(buffer, 0, buffer.Length);
handler.Response.Close();
};
await httpService.StartAsync();
在服务端类中处理客户端消息
所有服务端类都遵循一致的模式来处理客户端生命周期事件。OnClientMessage 事件针对以下三个步骤触发:
// 在任何服务端类中处理客户端消息的通用模式
void ConfigureService<TService, TData>(TService service)
where TService : CommunicationServiceAbstract
{
service.OnClientMessage += (sender, args) =>
{
switch (args.Step)
{
case var step when step.Equals(TcpServiceData.Steps.客户端连接):
// 客户端已连接 — 注册、记录日志或初始化会话
Console.WriteLine($"客户端已连接:{args.IpPort}");
break;
case var step when step.Equals(TcpServiceData.Steps.客户端断开):
// 客户端已断开 — 清理资源
Console.WriteLine($"客户端已断开:{args.IpPort}");
break;
case var step when step.Equals(TcpServiceData.Steps.消息接收):
// 消息已接收 — 处理并可选择回复
string message = Encoding.UTF8.GetString(args.Bytes);
Console.WriteLine($"消息内容:{message}");
// 回显响应
byte[] response = Encoding.UTF8.GetBytes($"回显:{message}");
service.SendToClientAsync(args.IpPort, response);
break;
}
};
}
