Smart.Ports 4.2.1

dotnet add package Smart.Ports --version 4.2.1
                    
NuGet\Install-Package Smart.Ports -Version 4.2.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Smart.Ports" Version="4.2.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Smart.Ports" Version="4.2.1" />
                    
Directory.Packages.props
<PackageReference Include="Smart.Ports" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Smart.Ports --version 4.2.1
                    
#r "nuget: Smart.Ports, 4.2.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Smart.Ports@4.2.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Smart.Ports&version=4.2.1
                    
Install as a Cake Addin
#tool nuget:?package=Smart.Ports&version=4.2.1
                    
Install as a Cake Tool

Smart.Ports

NuGet

项目介绍

Smart.Ports是一个统一的通信端口类库,提供了一致的接口来操作不同类型的通信端口,包括串口(SerialPort)、TCP客户端(TcpClient)、TCP服务端(TcpServer)和UDP节点(Udp)。该类库使用工厂模式简化端口创建,并通过继承关系提供特定端口类型的扩展功能。

核心接口

IPort

所有通信端口的基础接口,定义了通用的打开、关闭、发送和事件处理方法。

public interface IPort
{
    // 事件定义
    event Action<IPort, PortEventArgs> OnOpen;
    event Action<IPort, DataEventArgs> OnSend;
    event Action<IPort, DataEventArgs> OnReceive;
    event Action<IPort> OnClose;
    event Action<IPort, PortErrorArgs> OnError;
    
    // 属性
    string Name { get; set; }
    object? Tag { get; set; }
    bool IsOpen { get; }
    PortType PortType { get; }
    
    // 方法
    bool Open();
    bool Send(byte[] data);
    bool Close();
}

IServerPort

针对TCP服务端的特定接口,扩展了IPort接口,提供了客户端连接管理功能。

public interface IServerPort : IPort
{
    // 事件
    event Action<IServerPort, ConnectEventArgs> OnConnect;
    event Action<IServerPort, DisConnectEventArgs> OnDisConnect;
    
    // 方法
    List<nint> GetAllClientIds();
    bool IsConnected(nint clientId);
    bool Send(byte[] data, nint clientId);
    bool Disconnect(nint clientId);
    bool SetClientData(nint connId, object obj);
    T GetClientData<T>(nint connId);
    ConcurrentDictionary<nint, object> GetAllClientData();
    bool RemoveClientData(nint connId);
}

IUdpPort

针对UDP通信的特定接口,扩展了IPort接口,提供了指定端点发送数据的功能。

public interface IUdpPort : IPort
{
    bool Send(byte[] data, PortEndPoint endPoint);
}

实现类

  • SmartSerialPort - 串口通信实现
  • SmartTcpClient - TCP客户端实现
  • SmartTcpServer - TCP服务端实现
  • SmartUdpNode - UDP通信实现

端口配置(PortConfig)

通过PortConfig类配置不同类型的通信端口,每种端口类型有特定的参数格式:

串口参数格式

COM1;9600,8,N,1;None
  • 第一个部分:串口名称(如COM1)
  • 第二个部分:波特率,数据位,奇偶校验,停止位(如9600,8,N,1)
  • 第三个部分:流控方式(None, RequestToSend, XOnXOff等)

TCP客户端参数格式

127.0.0.1:5055
  • IP地址:端口号

TCP服务端参数格式

0.0.0.0:5055;10000
  • IP地址:端口号;最大连接数(最大连接数可选,默认10000)

UDP参数格式

0.0.0.0:5055
  • 监听的IP地址和端口号

事件参数

  • PortEventArgs - 基础打开事件参数
  • DataEventArgs - 基础数据事件参数
  • SerialPortEventArgs - 串口打开事件参数
  • ClientPortEventArgs - TCP客户端连接事件参数
  • ServerDataEventArgs - TCP服务端数据事件参数
  • UdpDataEventArgs - UDP数据事件参数
  • ConnectEventArgs - 客户端连接事件参数
  • DisConnectEventArgs - 客户端断开连接事件参数
  • PortErrorArgs - 错误事件参数

使用示例

创建并使用串口

// 创建串口配置
var serialConfig = new PortConfig(PortType.SerialPort, "COM3;9600,8,N,1;None");

// 使用工厂创建串口实例
var serialPort = PortFactory.CreatePort(serialConfig);

// 订阅事件
serialPort.OnOpen += (port, args) => Console.WriteLine("串口已打开");
serialPort.OnReceive += (port, args) =>
{
    string data = Encoding.ASCII.GetString(args.Data);
    Console.WriteLine($"接收到数据: {data}");
};
serialPort.OnError += (port, args) => Console.WriteLine($"错误: {args.Exception.Message}");

// 打开串口
serialPort.Open();

// 发送数据
byte[] sendData = Encoding.ASCII.GetBytes("Hello Smart.Ports!");
serialPort.Send(sendData);

// 关闭串口
// serialPort.Close();

创建并使用TCP客户端

// 创建TCP客户端配置
var tcpClientConfig = new PortConfig(PortType.TcpClient, "127.0.0.1:5055");

// 使用工厂创建TCP客户端实例
var tcpClient = PortFactory.CreatePort(tcpClientConfig);

// 订阅事件
tcpClient.OnOpen += (port, args) => Console.WriteLine("TCP客户端已连接");
tcpClient.OnReceive += (port, args) =>
{
    string data = Encoding.ASCII.GetString(args.Data);
    Console.WriteLine($"接收到数据: {data}");
};

// 连接服务器
tcpClient.Open();

// 发送数据
byte[] sendData = Encoding.ASCII.GetBytes("Hello TCP Server!");
tcpClient.Send(sendData);

创建并使用TCP服务端

// 创建TCP服务端配置
var tcpServerConfig = new PortConfig(PortType.TcpServer, "0.0.0.0:5055;10000");

// 使用工厂创建TCP服务端实例
var tcpServer = (IServerPort)PortFactory.CreatePort(tcpServerConfig);

// 订阅事件
tcpServer.OnOpen += (port, args) => Console.WriteLine("TCP服务端已启动");
tcpServer.OnConnect += (port, args) =>
    Console.WriteLine($"客户端已连接: {args.ClientId}");
tcpServer.OnReceive += (port, args) =>
{
    if (args is ServerDataEventArgs serverArgs)
    {
        string data = Encoding.ASCII.GetString(serverArgs.Data);
        Console.WriteLine($"从客户端 {serverArgs.ClientId} 接收到: {data}");
        
        // 回复客户端
        tcpServer.Send(Encoding.ASCII.GetBytes("收到!"), serverArgs.ClientId);
    }
};

// 启动服务端
tcpServer.Open();

创建并使用UDP节点

// 创建UDP配置
var udpConfig = new PortConfig(PortType.Udp, "0.0.0.0:5055");

// 使用工厂创建UDP实例
var udpNode = (IUdpPort)PortFactory.CreatePort(udpConfig);

// 订阅事件
udpNode.OnOpen += (port, args) => Console.WriteLine("UDP节点已启动");
udpNode.OnReceive += (port, args) =>
{
    if (args is UdpDataEventArgs udpArgs)
    {
        string data = Encoding.ASCII.GetString(udpArgs.Data);
        Console.WriteLine($"从 {udpArgs.EndPoint.Address}:{udpArgs.EndPoint.Port} 收到: {data}");
    }
};

// 启动UDP监听
udpNode.Open();

// 发送数据到特定端点
var remoteEndPoint = new PortEndPoint("127.0.0.1", 5056);
udpNode.Send(Encoding.ASCII.GetBytes("Hello UDP!"), remoteEndPoint);

注意事项

  1. 对于TCP服务端,使用Send(byte[], nint)方法发送数据到特定客户端
  2. 对于UDP通信,使用Send(byte[], PortEndPoint)方法发送数据到特定端点
  3. 所有端口实例都实现了IDisposable接口,建议在使用完毕后释放资源
  4. 错误处理通过OnError事件进行管理

项目结构

  • IPort.cs - 基础端口接口
  • IServerPort.cs - TCP服务端接口
  • IUdpPort.cs - UDP通信接口
  • PortConfig.cs - 端口配置类
  • PortFactory.cs - 端口工厂类
  • PortType.cs - 端口类型枚举
  • PortEndPoint.cs - 通信端点类
  • SmartSerialPort.cs - 串口实现
  • SmartTcpClient.cs - TCP客户端实现
  • SmartTcpServer.cs - TCP服务端实现
  • SmartUdpNode.cs - UDP实现
  • EventArgs/ - 事件参数类集合

Smart.Ports

Project Introduction

Smart.Ports is a unified communication port library that provides a consistent interface for operating different types of communication ports, including SerialPort, TcpClient, TcpServer, and Udp. The library uses the factory pattern to simplify port creation and provides extended functionality for specific port types through inheritance.

Core Interfaces

IPort

The base interface for all communication ports, defining common methods for opening, closing, sending, and event handling.

public interface IPort
{
    // Event definitions
    event Action<IPort, PortEventArgs> OnOpen;
    event Action<IPort, DataEventArgs> OnSend;
    event Action<IPort, DataEventArgs> OnReceive;
    event Action<IPort> OnClose;
    event Action<IPort, PortErrorArgs> OnError;
    
    // Properties
    string Name { get; set; }
    object? Tag { get; set; }
    bool IsOpen { get; }
    PortType PortType { get; }
    
    // Methods
    bool Open();
    bool Send(byte[] data);
    bool Close();
}

IServerPort

A specific interface for TCP servers, extending IPort with client connection management functionality.

public interface IServerPort : IPort
{
    // Events
    event Action<IServerPort, ConnectEventArgs> OnConnect;
    event Action<IServerPort, DisConnectEventArgs> OnDisConnect;
    
    // Methods
    List<nint> GetAllClientIds();
    bool IsConnected(nint clientId);
    bool Send(byte[] data, nint clientId);
    bool Disconnect(nint clientId);
    bool SetClientData(nint connId, object obj);
    T GetClientData<T>(nint connId);
    ConcurrentDictionary<nint, object> GetAllClientData();
    bool RemoveClientData(nint connId);
}

IUdpPort

A specific interface for UDP communication, extending IPort with functionality to send data to specific endpoints.

public interface IUdpPort : IPort
{
    bool Send(byte[] data, PortEndPoint endPoint);
}

Implementation Classes

  • SmartSerialPort - Serial port implementation
  • SmartTcpClient - TCP client implementation
  • SmartTcpServer - TCP server implementation
  • SmartUdpNode - UDP communication implementation

Port Configuration (PortConfig)

Configure different types of communication ports through the PortConfig class, each with specific parameter formats:

Serial Port Parameter Format

COM1;9600,8,N,1;None
  • First part: Serial port name (e.g., COM1)
  • Second part: Baud rate, data bits, parity, stop bits (e.g., 9600,8,N,1)
  • Third part: Flow control method (None, RequestToSend, XOnXOff, etc.)

TCP Client Parameter Format

127.0.0.1:5055
  • IP address:port number

TCP Server Parameter Format

0.0.0.0:5055;10000
  • IP address:port number;max connection count (max connection count is optional, default 10000)

UDP Parameter Format

0.0.0.0:5055
  • IP address and port number to listen on

Event Parameters

  • PortEventArgs - Basic open event parameters
  • DataEventArgs - Basic data event parameters
  • SerialPortEventArgs - Serial port open event parameters
  • ClientPortEventArgs - TCP client connection event parameters
  • ServerDataEventArgs - TCP server data event parameters
  • UdpDataEventArgs - UDP data event parameters
  • ConnectEventArgs - Client connection event parameters
  • DisConnectEventArgs - Client disconnection event parameters
  • PortErrorArgs - Error event parameters

Usage Examples

Creating and Using Serial Port

// Create serial port configuration
var serialConfig = new PortConfig(PortType.SerialPort, "COM3;9600,8,N,1;None");

// Create serial port instance using factory
var serialPort = PortFactory.CreatePort(serialConfig);

// Subscribe to events
serialPort.OnOpen += (port, args) => Console.WriteLine("Serial port opened");
serialPort.OnReceive += (port, args) =>
{
    string data = Encoding.ASCII.GetString(args.Data);
    Console.WriteLine($"Received data: {data}");
};
serialPort.OnError += (port, args) => Console.WriteLine($"Error: {args.Exception.Message}");

// Open the serial port
serialPort.Open();

// Send data
byte[] sendData = Encoding.ASCII.GetBytes("Hello Smart.Ports!");
serialPort.Send(sendData);

// Close the serial port
// serialPort.Close();

Creating and Using TCP Client

// Create TCP client configuration
var tcpClientConfig = new PortConfig(PortType.TcpClient, "127.0.0.1:5055");

// Create TCP client instance using factory
var tcpClient = PortFactory.CreatePort(tcpClientConfig);

// Subscribe to events
tcpClient.OnOpen += (port, args) => Console.WriteLine("TCP client connected");
tcpClient.OnReceive += (port, args) =>
{
    string data = Encoding.ASCII.GetString(args.Data);
    Console.WriteLine($"Received data: {data}");
};

// Connect to server
tcpClient.Open();

// Send data
byte[] sendData = Encoding.ASCII.GetBytes("Hello TCP Server!");
tcpClient.Send(sendData);

Creating and Using TCP Server

// Create TCP server configuration
var tcpServerConfig = new PortConfig(PortType.TcpServer, "0.0.0.0:5055;10000");

// Create TCP server instance using factory
var tcpServer = (IServerPort)PortFactory.CreatePort(tcpServerConfig);

// Subscribe to events
tcpServer.OnOpen += (port, args) => Console.WriteLine("TCP server started");
tcpServer.OnConnect += (port, args) =>
    Console.WriteLine($"Client connected: {args.ClientId}");
tcpServer.OnReceive += (port, args) =>
{
    if (args is ServerDataEventArgs serverArgs)
    {
        string data = Encoding.ASCII.GetString(serverArgs.Data);
        Console.WriteLine($"Received from client {serverArgs.ClientId}: {data}");
        
        // Reply to client
        tcpServer.Send(Encoding.ASCII.GetBytes("Received!"), serverArgs.ClientId);
    }
};

// Start server
tcpServer.Open();

Creating and Using UDP Node

// Create UDP configuration
var udpConfig = new PortConfig(PortType.Udp, "0.0.0.0:5055");

// Create UDP instance using factory
var udpNode = (IUdpPort)PortFactory.CreatePort(udpConfig);

// Subscribe to events
udpNode.OnOpen += (port, args) => Console.WriteLine("UDP node started");
udpNode.OnReceive += (port, args) =>
{
    if (args is UdpDataEventArgs udpArgs)
    {
        string data = Encoding.ASCII.GetString(udpArgs.Data);
        Console.WriteLine($"Received from {udpArgs.EndPoint.Address}:{udpArgs.EndPoint.Port}: {data}");
    }
};

// Start UDP listening
udpNode.Open();

// Send data to specific endpoint
var remoteEndPoint = new PortEndPoint("127.0.0.1", 5056);
udpNode.Send(Encoding.ASCII.GetBytes("Hello UDP!"), remoteEndPoint);

Notes

  1. For TCP servers, use the Send(byte[], nint) method to send data to specific clients
  2. For UDP communication, use the Send(byte[], PortEndPoint) method to send data to specific endpoints
  3. All port instances implement the IDisposable interface, so it is recommended to release resources after use
  4. Error handling is managed through the OnError event

Project Structure

  • IPort.cs - Base port interface
  • IServerPort.cs - TCP server interface
  • IUdpPort.cs - UDP communication interface
  • PortConfig.cs - Port configuration class
  • PortFactory.cs - Port factory class
  • PortType.cs - Port type enumeration
  • PortEndPoint.cs - Communication endpoint class
  • SmartSerialPort.cs - Serial port implementation
  • SmartTcpClient.cs - TCP client implementation
  • SmartTcpServer.cs - TCP server implementation
  • SmartUdpNode.cs - UDP implementation
  • EventArgs/ - Collection of event parameter classes
> Developed by zenglei
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.2.1 163 10/23/2025
4.2.0 157 10/23/2025
4.1.7-beta.4 111 10/23/2025
4.1.7-beta.3 117 10/16/2025
4.1.7-beta.2 115 10/15/2025
4.1.7-beta.1 118 10/9/2025
4.1.6 170 10/8/2025
4.1.5 154 9/7/2025
4.1.4 203 8/24/2025
4.1.3 275 7/26/2025
4.1.2 554 7/23/2025
4.1.1 260 7/20/2025
4.1.0 171 7/17/2025
4.0.1 112 7/5/2025
4.0.0 219 6/14/2025
4.0.0-beta.12 275 6/12/2025
4.0.0-beta.11 273 6/12/2025
4.0.0-beta.10 273 6/11/2025
4.0.0-beta.9 275 6/11/2025
4.0.0-beta.8 283 6/10/2025
4.0.0-beta.7 278 6/10/2025
4.0.0-beta.6 227 6/9/2025
4.0.0-beta.5 187 6/8/2025
4.0.0-beta.4 190 6/8/2025
4.0.0-beta.3 99 6/8/2025
4.0.0-beta.2 107 6/7/2025
4.0.0-beta.1 114 6/7/2025
3.1.0 209 6/1/2025
3.0.0 206 5/25/2025
2.0.0 120 4/5/2025
1.0.3 175 3/16/2025
1.0.2 177 2/26/2025
1.0.1 133 2/26/2025
1.0.0 167 2/25/2025
1.0.0-rc.2 88 2/25/2025
1.0.0-rc.1 88 2/24/2025
1.0.0-beta.4 62 2/24/2025
1.0.0-beta.3 88 2/23/2025
1.0.0-beta.2 81 2/23/2025
1.0.0-beta.1 83 2/23/2025