Smart.Ports是一个统一的通信端口类库,提供了一致的接口来操作不同类型的通信端口,包括串口(SerialPort)、TCP客户端(TcpClient)、TCP服务端(TcpServer)和UDP节点(Udp)。该类库使用工厂模式简化端口创建,并通过继承关系提供特定端口类型的扩展功能。 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.
License
—
Deps
9
Install Size
—
Vulns
✓ 0
Published
Mar 3, 2026
$ dotnet add package Smart.PortsSmart.Ports is a unified communication port library for .NET 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. It supports .NET 8, 9, and 10.
IPort provides a consistent API across all communication types.PortFactory simplifies port creation with configuration-based instantiation.IServerPort interface for managing multiple client connections.IUdpPort interface for sending data to specific remote endpoints.PortConfig class for easy port parameter configuration.Install the package via NuGet:
dotnet add package Smart.Ports
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();
}
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);
}
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);
}
Configure different types of communication ports through the PortConfig class, each with specific parameter formats:
COM1;9600,8,N,1;None
127.0.0.1:5055
0.0.0.0:5055;10000
0.0.0.0:5055
using Smart.Ports;
// 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.OnSend += (port, args) => Console.WriteLine($"Data sent: {args.Data.Length} bytes");
serialPort.OnReceive += (port, args) =>
{
string data = Encoding.ASCII.GetString(args.Data);
Console.WriteLine($"Received data: {data}");
};
serialPort.OnClose += (port) => Console.WriteLine("Serial port closed");
serialPort.OnError += (port, args) => Console.WriteLine($"Error: {args.Exception.Message}");
// Open the serial port
if (serialPort.Open())
{
Console.WriteLine("Serial port opened successfully");
// Send data
byte[] sendData = Encoding.ASCII.GetBytes("Hello Smart.Ports!");
serialPort.Send(sendData);
// Close when done
// serialPort.Close();
}
using Smart.Ports;
// 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.OnSend += (port, args) => Console.WriteLine($"Sent: {args.Data.Length} bytes");
tcpClient.OnReceive += (port, args) =>
{
string data = Encoding.ASCII.GetString(args.Data);
Console.WriteLine($"Received data: {data}");
};
tcpClient.OnError += (port, args) => Console.WriteLine($"Error: {args.Exception.Message}");
// Connect to server
if (tcpClient.Open())
{
Console.WriteLine("Connected to server");
// Send data
byte[] sendData = Encoding.ASCII.GetBytes("Hello TCP Server!");
tcpClient.Send(sendData);
}
using Smart.Ports;
// 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}");
// Store client-specific data
tcpServer.SetClientData(args.ClientId, $"Client_{args.ClientId}");
};
tcpServer.OnDisConnect += (port, args) =>
{
Console.WriteLine($"Client disconnected: {args.ClientId}");
// Clean up client data
tcpServer.RemoveClientData(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);
}
};
tcpServer.OnError += (port, args) => Console.WriteLine($"Error: {args.Exception.Message}");
// Start server
if (tcpServer.Open())
{
Console.WriteLine("Server is listening on 0.0.0.0:5055");
// Server will accept connections until closed
// tcpServer.Close();
}
using Smart.Ports;
// 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.OnSend += (port, args) => Console.WriteLine($"Sent: {args.Data.Length} bytes");
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}");
}
};
udpNode.OnError += (port, args) => Console.WriteLine($"Error: {args.Exception.Message}");
// Start UDP listening
if (udpNode.Open())
{
Console.WriteLine("UDP node is listening on 0.0.0.0:5055");
// Send data to specific endpoint
var remoteEndPoint = new PortEndPoint("127.0.0.1", 5056);
udpNode.Send(Encoding.ASCII.GetBytes("Hello UDP!"), remoteEndPoint);
}
using Smart.Ports;
var tcpServer = (IServerPort)PortFactory.CreatePort(
new PortConfig(PortType.TcpServer, "0.0.0.0:8080;100")
);
tcpServer.OnConnect += (server, args) =>
{
// Store client-specific information
var clientInfo = new
{
ConnectedAt = DateTime.Now,
RemoteEndPoint = args.RemoteEndPoint
};
server.SetClientData(args.ClientId, clientInfo);
Console.WriteLine($"Client {args.ClientId} connected from {clientInfo.RemoteEndPoint}");
};
tcpServer.OnReceive += (server, args) =>
{
if (args is ServerDataEventArgs serverArgs)
{
// Retrieve client data
var clientInfo = server.GetClientData<dynamic>(serverArgs.ClientId);
Console.WriteLine($"Data from {clientInfo.ConnectedAt}: {Encoding.ASCII.GetString(serverArgs.Data)}");
// Broadcast to all connected clients
foreach (var clientId in server.GetAllClientIds())
{
if (clientId != serverArgs.ClientId)
{
server.Send(serverArgs.Data, clientId);
}
}
}
};
tcpServer.Open();
The library provides various event argument classes for different scenarios:
byte[] Data)nint ClientId)PortEndPoint EndPoint)nint ClientId, string RemoteEndPoint)nint ClientId)Exception Exception)IDisposable. Always dispose of ports when done or use using statements.using var port = PortFactory.CreatePort(config);
port.Open();
// Use the port...
// Automatically disposed
Error Handling: Always subscribe to the OnError event to handle exceptions gracefully.
Thread Safety: All port implementations are thread-safe, but ensure your event handlers are also thread-safe if they access shared resources.
TCP Server Client Management: Use SetClientData and GetClientData to store client-specific information for efficient management.
UDP Communication: Remember that UDP is connectionless. Always specify the target endpoint when sending data.
Smart.Ports/
├── Interfaces/
│ ├── IPort.cs - Base port interface
│ ├── IServerPort.cs - TCP server interface
│ └── IUdpPort.cs - UDP communication interface
├── Core/
│ ├── PortConfig.cs - Port configuration class
│ ├── PortFactory.cs - Port factory class
│ ├── PortType.cs - Port type enumeration
│ └── PortEndPoint.cs - Communication endpoint class
├── Implementations/
│ ├── SmartSerialPort.cs - Serial port implementation
│ ├── SmartTcpClient.cs - TCP client implementation
│ ├── SmartTcpServer.cs - TCP server implementation
│ └── SmartUdpNode.cs - UDP implementation
└── EventArgs/
├── PortEventArgs.cs - Basic open event parameters
├── DataEventArgs.cs - Basic data event parameters
├── SerialPortEventArgs.cs
├── ClientPortEventArgs.cs
├── ServerDataEventArgs.cs
├── UdpDataEventArgs.cs
├── ConnectEventArgs.cs
├── DisConnectEventArgs.cs
└── PortErrorArgs.cs
Smart.Ports 是一个用于 .NET 的统一通信端口类库,提供了一致的接口来操作不同类型的通信端口,包括串口(SerialPort)、TCP客户端(TcpClient)、TCP服务端(TcpServer)和UDP节点(Udp)。该类库使用工厂模式简化端口创建,并通过继承关系提供特定端口类型的扩展功能。它支持 .NET 8, 9 和 10。
IPort 为所有通信类型提供一致的 API。PortFactory 通过基于配置的实例化简化端口创建。IServerPort 接口用于管理多个客户端连接。IUdpPort 接口用于向特定远程端点发送数据。PortConfig 类用于轻松配置端口参数。通过 NuGet 安装:
dotnet add package Smart.Ports
所有通信端口的基础接口,定义了通用的打开、关闭、发送和事件处理方法。
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();
}
针对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);
}
针对UDP通信的特定接口,扩展了IPort接口,提供了指定端点发送数据的功能。
public interface IUdpPort : IPort
{
bool Send(byte[] data, PortEndPoint endPoint);
}
通过 PortConfig 类配置不同类型的通信端口,每种端口类型有特定的参数格式:
COM1;9600,8,N,1;None
127.0.0.1:5055
0.0.0.0:5055;10000
0.0.0.0:5055
using Smart.Ports;
// 创建串口配置
var serialConfig = new PortConfig(PortType.SerialPort, "COM3;9600,8,N,1;None");
// 使用工厂创建串口实例
var serialPort = PortFactory.CreatePort(serialConfig);
// 订阅事件
serialPort.OnOpen += (port, args) => Console.WriteLine("串口已打开");
serialPort.OnSend += (port, args) => Console.WriteLine($"已发送: {args.Data.Length} 字节");
serialPort.OnReceive += (port, args) =>
{
string data = Encoding.ASCII.GetString(args.Data);
Console.WriteLine($"接收到数据: {data}");
};
serialPort.OnClose += (port) => Console.WriteLine("串口已关闭");
serialPort.OnError += (port, args) => Console.WriteLine($"错误: {args.Exception.Message}");
// 打开串口
if (serialPort.Open())
{
Console.WriteLine("串口打开成功");
// 发送数据
byte[] sendData = Encoding.ASCII.GetBytes("Hello Smart.Ports!");
serialPort.Send(sendData);
// 使用完毕后关闭
// serialPort.Close();
}
using Smart.Ports;
// 创建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.OnSend += (port, args) => Console.WriteLine($"已发送: {args.Data.Length} 字节");
tcpClient.OnReceive += (port, args) =>
{
string data = Encoding.ASCII.GetString(args.Data);
Console.WriteLine($"接收到数据: {data}");
};
tcpClient.OnError += (port, args) => Console.WriteLine($"错误: {args.Exception.Message}");
// 连接服务器
if (tcpClient.Open())
{
Console.WriteLine("已连接到服务器");
// 发送数据
byte[] sendData = Encoding.ASCII.GetBytes("Hello TCP Server!");
tcpClient.Send(sendData);
}
using Smart.Ports;
// 创建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.SetClientData(args.ClientId, $"Client_{args.ClientId}");
};
tcpServer.OnDisConnect += (port, args) =>
{
Console.WriteLine($"客户端已断开: {args.ClientId}");
// 清理客户端数据
tcpServer.RemoveClientData(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.OnError += (port, args) => Console.WriteLine($"错误: {args.Exception.Message}");
// 启动服务端
if (tcpServer.Open())
{
Console.WriteLine("服务端正在监听 0.0.0.0:5055");
// 服务端将接受连接直到关闭
// tcpServer.Close();
}
using Smart.Ports;
// 创建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.OnSend += (port, args) => Console.WriteLine($"已发送: {args.Data.Length} 字节");
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}");
}
};
udpNode.OnError += (port, args) => Console.WriteLine($"错误: {args.Exception.Message}");
// 启动UDP监听
if (udpNode.Open())
{
Console.WriteLine("UDP节点正在监听 0.0.0.0:5055");
// 发送数据到特定端点
var remoteEndPoint = new PortEndPoint("127.0.0.1", 5056);
udpNode.Send(Encoding.ASCII.GetBytes("Hello UDP!"), remoteEndPoint);
}
using Smart.Ports;
var tcpServer = (IServerPort)PortFactory.CreatePort(
new PortConfig(PortType.TcpServer, "0.0.0.0:8080;100")
);
tcpServer.OnConnect += (server, args) =>
{
// 存储客户端特定信息
var clientInfo = new
{
ConnectedAt = DateTime.Now,
RemoteEndPoint = args.RemoteEndPoint
};
server.SetClientData(args.ClientId, clientInfo);
Console.WriteLine($"客户端 {args.ClientId} 从 {clientInfo.RemoteEndPoint} 连接");
};
tcpServer.OnReceive += (server, args) =>
{
if (args is ServerDataEventArgs serverArgs)
{
// 获取客户端数据
var clientInfo = server.GetClientData<dynamic>(serverArgs.ClientId);
Console.WriteLine($"来自 {clientInfo.ConnectedAt} 的数据: {Encoding.ASCII.GetString(serverArgs.Data)}");
// 广播到所有连接的客户端
foreach (var clientId in server.GetAllClientIds())
{
if (clientId != serverArgs.ClientId)
{
server.Send(serverArgs.Data, clientId);
}
}
}
};
tcpServer.Open();
该库为不同场景提供了各种事件参数类:
byte[] Data)nint ClientId)PortEndPoint EndPoint)nint ClientId, string RemoteEndPoint)nint ClientId)Exception Exception)IDisposable。使用完毕后务必释放端口或使用 using 语句。using var port = PortFactory.CreatePort(config);
port.Open();
// 使用端口...
// 自动释放
错误处理: 始终订阅 OnError 事件以优雅地处理异常。
线程安全: 所有端口实现都是线程安全的,但如果事件处理器访问共享资源,请确保它们也是线程安全的。
TCP服务端客户端管理: 使用 SetClientData 和 GetClientData 存储客户端特定信息以实现高效管理。
UDP通信: 记住UDP是无连接的。发送数据时始终指定目标端点。
Smart.Ports/
├── Interfaces/
│ ├── IPort.cs - 基础端口接口
│ ├── IServerPort.cs - TCP服务端接口
│ └── IUdpPort.cs - UDP通信接口
├── Core/
│ ├── PortConfig.cs - 端口配置类
│ ├── PortFactory.cs - 端口工厂类
│ ├── PortType.cs - 端口类型枚举
│ └── PortEndPoint.cs - 通信端点类
├── Implementations/
│ ├── SmartSerialPort.cs - 串口实现
│ ├── SmartTcpClient.cs - TCP客户端实现
│ ├── SmartTcpServer.cs - TCP服务端实现
│ └── SmartUdpNode.cs - UDP实现
└── EventArgs/
├── PortEventArgs.cs - 基础打开事件参数
├── DataEventArgs.cs - 基础数据事件参数
├── SerialPortEventArgs.cs
├── ClientPortEventArgs.cs
├── ServerDataEventArgs.cs
├── UdpDataEventArgs.cs
├── ConnectEventArgs.cs
├── DisConnectEventArgs.cs
└── PortErrorArgs.cs
Developed by zenglei