🔌 WebSocket 传输
命名空间: Snet.Core.communication.net.ws | 类: WsClientOperate, WsServiceOperate
WsClientOperate — WebSocket 客户端
继承: CommunicationAbstract<WsClientOperate, WsClientData.Basics> | 接口: ICommunication
配置 (WsClientData.Basics)
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Host |
string |
"ws://127.0.0.1:6688/" |
WebSocket 服务器 URL |
InterruptReconnection |
bool |
true |
自动重连 |
ReconnectionInterval |
int |
1000 |
重连间隔 (ms) |
Timeout |
int |
1000 |
I/O 超时 (ms) |
SendWaitInterval |
int |
5000 |
发送等待超时 (ms) |
MaxChunkSize |
int |
261120 |
每块最大字节数 |
RetrySendCount |
int |
5 |
每块重试次数 |
BufferSize |
int |
1048576 |
接收缓冲区 (1MB) |
关键特性
- 基于
ClientWebSocket - 指数退避重连 (500ms→30s)
- 优雅关闭:
CloseAsync超时 →Abort回退 MonitorAsync循环接收帧,检测对端关闭 (ReceiveAsync 返回 0 字节)
使用示例
using Snet.Core.communication.net.ws.client;
using static Snet.Core.communication.net.ws.client.WsClientData;
var config = new Basics { Host = "ws://192.168.1.100:8080/ws" };
var ws = await WsClientOperate.InstanceAsync(config);
await ws.OnAsync();
await ws.SendAsync(Encoding.UTF8.GetBytes("hello"));
await ws.OffAsync();
WsServiceOperate — WebSocket 服务端
继承: CommunicationServiceAbstract<WsServiceOperate, WsServiceData.Basics> | 接口: ICommunicationService
配置 (WsServiceData.Basics)
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
Host |
string |
"ws://127.0.0.1:6688/" |
监听地址 (ws://→http://) |
MaxChunkSize |
int |
261120 |
每块最大字节数 |
RetrySendCount |
int |
5 |
每块重试次数 |
Timeout |
int |
1000 |
I/O 超时 (ms) |
BufferSize |
int |
1048576 |
接收缓冲区 (1MB) |
客户端事件
ClientMessage 额外包含 ClientId 字段用于 WebSocket 客户端识别。
使用示例
using Snet.Core.communication.net.ws.service;
using static Snet.Core.communication.net.ws.service.WsServiceData;
var config = new Basics { Host = "ws://0.0.0.0:8080/" };
var server = await WsServiceOperate.InstanceAsync(config);
server.OnDataEvent += (s, e) => {
if (e.ResultData is ClientMessage msg)
Console.WriteLine($"[{msg.Step}] {msg.IpPort} ClientId={msg.ClientId}");
};
await server.OnAsync();
await server.SendAsync(Encoding.UTF8.GetBytes("welcome")); // 群发
await server.OffAsync();
