通信类 - Snet Docs

🌐 通信类

概述

Snet 框架提供 11 个通信类,涵盖 TCP、UDP(单播/广播/组播)、WebSocket、HTTP 和串口通信。所有通信类使用嵌套的 Basics 类进行配置,通过构造函数传入。大部分客户端类继承自 CommunicationAbstract(实现 ICommunication 接口)。大部分服务端类继承自 CommunicationServiceAbstract(实现 ICommunicationService 接口)。HTTP 客户端和服务端类直接继承自 CoreUnify


快速参考

| 类 | 类型 | 基类 | 关键协议 | 默认端口 | |---|------|------|---------|---------| | TcpClientOperate | 客户端 | CommunicationAbstract | TCP | 6688 | | UdpClientOperate | 客户端 | CommunicationAbstract | UDP 单播 | 6688 | | UdpBroadcastOperate | 客户端 | CommunicationAbstract | UDP 广播 | 6688(绑定)/ 8866(发送) | | UdpMulticastOperate | 客户端 | CommunicationAbstract | UDP 组播 | 6688(绑定)/ 8866(发送) | | WsClientOperate | 客户端 | CommunicationAbstract | WebSocket | 6688 | | HttpClientOperate | 客户端 | CoreUnify | HTTP | 不适用 | | SerialOperate | 客户端 | CommunicationAbstract | 串口 | 不适用 | | TcpServiceOperate | 服务端 | CommunicationServiceAbstract | TCP | 6688 | | UdpServiceOperate | 服务端 | CommunicationServiceAbstract | UDP 单播 | 6688 | | WsServiceOperate | 服务端 | CommunicationServiceAbstract | WebSocket | 6688 | | HttpServiceOperate | 服务端 | CoreUnify | HTTP | 6688 |

客户端类

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 = await TcpClientOperate.InstanceAsync(new TcpClientData.Basics
{
    IpAddress = "192.168.1.100",
    Port = 6688,
    BufferSize = 1024 * 1024
});

var connectResult = await tcpClient.OnAsync();
if (connectResult.Status)
{
    // 处理数据事件
    tcpClient.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is byte[] data)
        {
            Console.WriteLine($"收到消息:{Encoding.UTF8.GetString(data)}");
        }
    };

    // 发送数据
    byte[] sendData = Encoding.UTF8.GetBytes("你好,TCP 服务器!");
    var sendResult = await tcpClient.SendAsync(sendData);
}

// 稍后:断开连接
await tcpClient.OffAsync();

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 = await UdpClientOperate.InstanceAsync(new UdpClientData.Basics
{
    IpAddress = "192.168.1.100",
    Port = 6688,
    LocalPort = 0  // 系统自动分配本地端口
});

var connectResult = await udpClient.OnAsync();
if (connectResult.Status)
{
    // 处理数据事件
    udpClient.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is byte[] data)
        {
            Console.WriteLine($"收到消息:{Encoding.UTF8.GetString(data)}");
        }
    };

    // 发送数据
    byte[] sendData = Encoding.UTF8.GetBytes("UDP 消息");
    await udpClient.SendAsync(sendData);
}

// 稍后:断开连接
await udpClient.OffAsync();

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

// 创建并配置 UDP 广播客户端
var broadcast = await UdpBroadcastOperate.InstanceAsync(new UdpBroadcastData.Basics
{
    Port = 6688,                    // 本地绑定端口
    BroadcastPort = 8866,           // 目标广播端口
    BroadcastAddress = "255.255.255.255"
});

var connectResult = await broadcast.OnAsync();
if (connectResult.Status)
{
    // 处理数据事件
    broadcast.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is byte[] data)
        {
            string received = Encoding.UTF8.GetString(data);
            Console.WriteLine($"广播回复:{received}");
        }
    };

    // 发送广播数据
    byte[] broadcastData = Encoding.UTF8.GetBytes("向所有设备广播消息");
    await broadcast.SendAsync(broadcastData);
}

// 稍后:断开连接
await broadcast.OffAsync();

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

// 创建并配置 UDP 组播客户端
var multicast = await UdpMulticastOperate.InstanceAsync(new UdpMulticastData.Basics
{
    Port = 6688,                    // 本地绑定端口
    MulticastAddress = "239.0.0.1",
    MulticastPort = 8866,           // 目标组播端口
    TimeToLive = 1                  // 仅本地子网
});

var connectResult = await multicast.OnAsync();
if (connectResult.Status)
{
    // 处理数据事件
    multicast.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is byte[] data)
        {
            Console.WriteLine($"组播收到:{Encoding.UTF8.GetString(data)}");
        }
    };

    // 发送组播数据
    byte[] multicastData = Encoding.UTF8.GetBytes("组播组消息");
    await multicast.SendAsync(multicastData);
}

// 稍后:断开连接
await multicast.OffAsync();

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 数据缓冲区大小
// 创建并连接 WebSocket 客户端
var wsClient = await WsClientOperate.InstanceAsync(new WsClientData.Basics
{
    Host = "ws://192.168.1.100:6688/",
    InterruptReconnection = true,
    ReconnectionInterval = 1000
});

var connectResult = await wsClient.OnAsync();
if (connectResult.Status)
{
    // 处理数据事件
    wsClient.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is byte[] data)
        {
            Console.WriteLine($"WebSocket 收到:{Encoding.UTF8.GetString(data)}");
        }
    };

    // 发送数据
    byte[] wsData = Encoding.UTF8.GetBytes("WebSocket 消息");
    await wsClient.SendAsync(wsData);
}

// 稍后:断开连接
await wsClient.OffAsync();

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 UrlHeadersDictionary)、MethodHttpMethod)、BodyTypeBType)、BodyContentobject)、EncodingEncoding)、ContentTypestring)、TimeOutTimeSpan)、ProxyIWebProxy?)、CookieContainer

  • ResponseData StatusCodeint)、ResHeadersDatasDictionary)、ResCookieDataCookieCollection)、ResDatastring?)、ReqDataRequestData

// 使用 HttpClientOperate 发起 HTTP 请求
var httpClient = await HttpClientOperate.InstanceAsync(new HttpClientData.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.RequestAsync(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 = await SerialOperate.InstanceAsync(new SerialData.Basics
{
    PortName = "COM3",
    BaudRate = 9600,
    ParityBit = Parity.None,
    DataBit = 8,
    StopBit = StopBits.One,
    ReadTimeout = 1000,
    WriteTimeout = 1000
});

var connectResult = await serial.OnAsync();
if (connectResult.Status)
{
    // 处理数据事件
    serial.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is byte[] data)
        {
            Console.WriteLine($"串口响应:{Encoding.ASCII.GetString(data)}");
        }
    };

    // 发送数据
    byte[] serialData = Encoding.ASCII.GetBytes("AT\r\n");
    await serial.SendAsync(serialData);
}

// 获取可用端口
string[] availablePorts = SerialOperate.GetPortArray();
Console.WriteLine($"可用端口:{string.Join("、", availablePorts)}");

// 稍后:断开连接
await serial.OffAsync();

服务端类

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 StepIpPortBytes
  • Steps 枚举: 客户端连接客户端断开消息接收
// 使用 TcpServiceOperate 创建 TCP 服务器
var tcpService = await TcpServiceOperate.InstanceAsync(new TcpServiceData.Basics
{
    IpAddress = "127.0.0.1",
    Port = 6688,
    MaxNumber = 1000,
    BufferSize = 1024 * 1024
});

// 处理客户端事件
tcpService.OnDataEvent += (sender, e) =>
{
    if (e.Status && e.ResultData is TcpServiceData.ClientMessage msg)
    {
        switch (msg.Step)
        {
            case Steps.客户端连接:
                Console.WriteLine($"客户端已连接:{msg.IpPort}");
                break;
            case Steps.客户端断开:
                Console.WriteLine($"客户端已断开:{msg.IpPort}");
                break;
            case Steps.消息接收:
                string message = Encoding.UTF8.GetString(msg.Bytes);
                Console.WriteLine($"来自 {msg.IpPort} 的消息:{message}");
                // 回显消息
                byte[] response = Encoding.UTF8.GetBytes($"回显:{message}");
                tcpService.SendAsync(response, msg.IpPort);
                break;
        }
    }
};

// 启动服务
var startResult = await tcpService.OnAsync();

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 StepIpPortBytes
  • Steps 枚举: 客户端连接客户端断开消息接收
// 使用 UdpServiceOperate 创建 UDP 服务器
var udpService = await UdpServiceOperate.InstanceAsync(new UdpServiceData.Basics
{
    IpAddress = "127.0.0.1",
    Port = 6688
});

// 处理客户端事件
udpService.OnDataEvent += (sender, e) =>
{
    if (e.Status && e.ResultData is UdpServiceData.ClientMessage msg)
    {
        switch (msg.Step)
        {
            case Steps.客户端连接:
                Console.WriteLine($"UDP 客户端已注册:{msg.IpPort}");
                break;
            case Steps.客户端断开:
                Console.WriteLine($"UDP 客户端已移除:{msg.IpPort}");
                break;
            case Steps.消息接收:
                string message = Encoding.UTF8.GetString(msg.Bytes);
                Console.WriteLine($"来自 {msg.IpPort} 的 UDP 消息:{message}");
                break;
        }
    }
};

// 启动服务
var startResult = await udpService.OnAsync();

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 StepIpPortBytes
  • Steps 枚举: 客户端连接客户端断开消息接收
// 创建 WebSocket 服务
var wsService = await WsServiceOperate.InstanceAsync(new WsServiceData.Basics
{
    Host = "ws://127.0.0.1:6688/",
    BufferSize = 1024 * 1024
});

// 处理客户端事件
wsService.OnDataEvent += (sender, e) =>
{
    if (e.Status && e.ResultData is WsServiceData.ClientMessage msg)
    {
        switch (msg.Step)
        {
            case Steps.客户端连接:
                Console.WriteLine($"WebSocket 客户端已连接。IpPort:{msg.IpPort}");
                byte[] welcome = Encoding.UTF8.GetBytes("欢迎连接到 WebSocket 服务器!");
                wsService.SendAsync(welcome, msg.IpPort);
                break;
            case Steps.客户端断开:
                Console.WriteLine($"WebSocket 客户端已断开。IpPort:{msg.IpPort}");
                break;
            case Steps.消息接收:
                string message = Encoding.UTF8.GetString(msg.Bytes);
                Console.WriteLine($"来自 {msg.IpPort} 的 WebSocket 消息:{message}");
                break;
        }
    }
};

// 启动服务
var startResult = await wsService.OnAsync();

HttpServiceOperate

命名空间: Snet.Core.communication.net.http.service 数据类: HttpServiceData.Basics(继承自 WAModel,继承属性 IpAddress="127.0.0.1"Port=6688CrossDomain=false

属性 类型 默认值 描述
SN string Guid 唯一标识符
Method HttpMethod Get 请求与响应的方式
ContentType string "application/json" 请求与响应的内容类型
AbsolutePaths List<string> ["/api/snet"] 接口的绝对路径集合

方法: SET(WAModel) — 快速设置 API 模型参数。

其他嵌套类型:

  • HttpServiceData.WaitHandler HttpListenerRequest RequestHttpListenerResponse Responsestring? BodyData
// 使用 HttpServiceOperate 设置 HTTP API 服务
var httpService = await HttpServiceOperate.InstanceAsync(new HttpServiceData.Basics
{
    IpAddress = "127.0.0.1",
    Port = 6688,
    AbsolutePaths = new List<string> { "/api/snet", "/api/data" },
    Method = HttpMethod.Post,
    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();
};

// 启动服务
var startResult = await httpService.OnAsync();

在服务端类中处理客户端消息

所有服务端类都遵循一致的模式通过 OnDataEvent 事件来处理客户端生命周期事件:

// 在任何服务端类中处理客户端消息的通用模式
void ConfigureService<TService, TBasics>(TService service)
    where TService : CoreUnify<TService, TBasics>
{
    service.OnDataEvent += (sender, e) =>
    {
        if (e.Status && e.ResultData is ClientMessage msg)
        {
            switch (msg.Step)
            {
                case Steps.客户端连接:
                    // 客户端已连接 — 注册、记录日志或初始化会话
                    Console.WriteLine($"客户端已连接:{msg.IpPort}");
                    break;

                case Steps.客户端断开:
                    // 客户端已断开 — 清理资源
                    Console.WriteLine($"客户端已断开:{msg.IpPort}");
                    break;

                case Steps.消息接收:
                    // 消息已接收 — 处理并可选择回复
                    string message = Encoding.UTF8.GetString(msg.Bytes);
                    Console.WriteLine($"消息内容:{message}");

                    // 回显响应
                    byte[] response = Encoding.UTF8.GetBytes($"回显:{message}");
                    service.SendAsync(response, msg.IpPort);
                    break;
            }
        }
    };
}

另请参阅