IceTea.SocketStandard
2.0.9
dotnet add package IceTea.SocketStandard --version 2.0.9
NuGet\Install-Package IceTea.SocketStandard -Version 2.0.9
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="IceTea.SocketStandard" Version="2.0.9" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="IceTea.SocketStandard" Version="2.0.9" />
<PackageReference Include="IceTea.SocketStandard" />
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 IceTea.SocketStandard --version 2.0.9
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: IceTea.SocketStandard, 2.0.9"
#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 IceTea.SocketStandard@2.0.9
#: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=IceTea.SocketStandard&version=2.0.9
#tool nuget:?package=IceTea.SocketStandard&version=2.0.9
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
IceTea.SocketStandard (Socket 标准通信类库)
简介
IceTea.SocketStandard 是一个标准化的 Socket 通信类库,提供了 TCP 和 UDP 协议的高级封装。该库支持同步和异步通信、SSL/TLS 加密、断线重连等企业级特性,适用于构建可靠的网络通信应用。
安装
dotnet add package IceTea.SocketStandard
核心功能模块
一、核心接口
ISocket (Socket通信接口)
定义了Socket通信的基础接口。
继承接口:
IStarter- 启动器接口ISend- 发送接口IEncoding- 编码接口IExceptionPublisher<string>- 异常发布接口INotifyPropertyChanged- 属性变更通知IDisposable- 资源释放接口
核心事件:
Action<EndPoint, EndPoint, byte[]> ReceivedMessage- 接收消息事件Action<EndPoint, EndPoint, byte[]> SentMessage- 发送消息事件
核心属性:
bool IsConnected { get; }- 连接状态IPEndPoint LocalOrServerPoint { get; }- 本地或服务器端点string Name { get; }- Socket名称uint MessageMaxLength { get; }- 最大消息长度
核心方法:
NetworkStream GetStream()- 获取网络流
二、TCP通信
NewTcpClient - TCP客户端
功能丰富的TCP客户端实现。
核心特性:
- 自动断线重连机制
- SSL/TLS加密支持
- 异步通信操作
- 连接状态监控
核心属性:
bool TryReConnect- 是否启用断线重连bool IsTryConnecting- 是否正在重连int ReConnectPeriodMilliseconds- 重连间隔时间
NewTcpServer - TCP服务器
TCP服务器端实现。
核心特性:
- 多客户端连接管理
- 广播消息支持
- 客户端生命周期管理
- 连接统计信息
三、UDP通信
UDP客户端和服务端实现
提供UDP协议的通信支持。
四、工具类
SocketUtility - Socket工具类
提供Socket相关的辅助功能。
使用指南
1. TCP客户端使用示例
// 创建TCP客户端
var tcpClient = new NewTcpClient(
tryReConnect: true,
serverIp: "192.168.1.100",
serverPort: 8080,
name: "MyClient"
);
// 监听接收消息
tcpClient.ReceivedMessage += (from, to, data) =>
{
var message = Encoding.UTF8.GetString(data);
Console.WriteLine($"收到消息: {message}");
Console.WriteLine($"来自: {from}, 发往: {to}");
};
// 监听连接状态变化
tcpClient.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == nameof(tcpClient.IsConnected))
{
Console.WriteLine($"连接状态: {tcpClient.IsConnected}");
}
};
// 启动连接
bool connected = await tcpClient.StartAsync();
if (connected)
{
// 发送消息
await tcpClient.SendAsync("Hello Server!");
// 发送二进制数据
var binaryData = new byte[] { 0x01, 0x02, 0x03, 0x04 };
await tcpClient.SendAsync(binaryData);
}
2. TCP服务器使用示例
// 创建TCP服务器
var tcpServer = new NewTcpServer(
port: 8080,
name: "MyServer"
);
// 监听客户端连接
tcpServer.ClientConnected += (clientInfo) =>
{
Console.WriteLine($"客户端连接: {clientInfo.EndPoint}");
};
// 监听客户端断开
tcpServer.ClientDisconnected += (clientInfo) =>
{
Console.WriteLine($"客户端断开: {clientInfo.EndPoint}");
};
// 监听接收消息
tcpServer.ReceivedMessage += (from, to, data) =>
{
var message = Encoding.UTF8.GetString(data);
Console.WriteLine($"收到消息: {message}");
// 回复客户端
tcpServer.SendToAsync(from, $"已收到: {message}");
};
// 启动服务器
bool started = await tcpServer.StartAsync();
if (started)
{
Console.WriteLine("服务器启动成功");
// 广播消息给所有客户端
await tcpServer.BroadcastAsync("服务器公告: 系统维护将在晚上10点进行");
}
3. SSL/TLS加密通信
// 客户端启用SSL
var secureClient = new NewTcpClient(serverIp: "secure.server.com", serverPort: 443);
// 配置SSL证书(服务器端)
// secureClient.UseSsl("server.crt"); // 需要先配置证书
// 启动安全连接
bool connected = await secureClient.StartAsync();
4. 断线重连配置
var client = new NewTcpClient(
tryReConnect: true,
serverIp: "192.168.1.100",
serverPort: 8080
)
{
ReConnectPeriodMilliseconds = 3000 // 3秒重连间隔
};
// 监听重连状态
client.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == nameof(client.IsTryConnecting))
{
if (client.IsTryConnecting)
{
Console.WriteLine("正在尝试重连...");
}
else
{
Console.WriteLine("重连完成");
}
}
};
5. UDP通信示例
// UDP客户端
var udpClient = new UdpClientWrapper();
// 发送UDP消息
await udpClient.SendToAsync("192.168.1.100", 9090, "Hello UDP!");
// UDP服务器
var udpServer = new UdpServerWrapper(port: 9090);
udpServer.ReceivedMessage += (from, to, data) =>
{
var message = Encoding.UTF8.GetString(data);
Console.WriteLine($"UDP收到: {message}");
};
技术特性
连接管理
- 自动重连: 断线后自动尝试重新连接
- 连接状态监控: 实时监控连接状态变化
- 优雅关闭: 支持正常的连接关闭流程
- 超时处理: 连接和操作超时机制
安全特性
- SSL/TLS支持: 加密通信保护数据安全
- 证书验证: 服务器证书验证机制
- 数据完整性: 传输过程中数据完整性保护
性能优化
- 异步操作: 全异步API设计提高并发性能
- 缓冲区管理: 高效的内存缓冲区管理
- 连接池: 连接复用减少建立连接开销
可靠性保障
- 心跳机制: 定期检测连接活性
- 异常处理: 完善的异常捕获和处理
- 日志记录: 详细的通信日志记录
典型应用场景
- 实时通信: 聊天应用、实时数据传输
- 物联网: 设备间通信、传感器数据采集
- 游戏开发: 实时多人游戏通信
- 金融交易: 高频交易系统通信
- 工业控制: 设备远程控制和监控
最佳实践
1. 连接管理
public class NetworkService : IDisposable
{
private readonly NewTcpClient _client;
private readonly ILogger _logger;
public NetworkService(ILogger logger)
{
_logger = logger;
_client = new NewTcpClient(tryReConnect: true);
_client.ReceivedMessage += OnMessageReceived;
_client.ExceptionOccurred += OnException;
_client.PropertyChanged += OnPropertyChanged;
}
private void OnMessageReceived(EndPoint from, EndPoint to, byte[] data)
{
try
{
var message = Encoding.UTF8.GetString(data);
_logger.Info($"收到消息: {message}");
// 处理业务逻辑
}
catch (Exception ex)
{
_logger.Error("消息处理失败", ex);
}
}
private void OnException(string remotePoint, Exception ex)
{
_logger.Error($"通信异常 [{remotePoint}]: {ex.Message}", ex);
}
public void Dispose()
{
_client?.Dispose();
}
}
2. 消息协议设计
public class MessageProtocol
{
// 消息头格式:长度(4字节) + 类型(1字节) + 数据
public static byte[] PackMessage(MessageType type, byte[] data)
{
var header = new byte[5];
var lengthBytes = BitConverter.GetBytes(data.Length);
Array.Copy(lengthBytes, header, 4);
header[4] = (byte)type;
var message = new byte[header.Length + data.Length];
Array.Copy(header, message, header.Length);
Array.Copy(data, 0, message, header.Length, data.Length);
return message;
}
public static (MessageType type, byte[] data) UnpackMessage(byte[] message)
{
if (message.Length < 5) throw new ArgumentException("消息格式错误");
var length = BitConverter.ToInt32(message, 0);
var type = (MessageType)message[4];
var data = new byte[length];
Array.Copy(message, 5, data, 0, length);
return (type, data);
}
}
3. 心跳保活
public class HeartbeatManager
{
private readonly ISocket _socket;
private readonly Timer _heartbeatTimer;
private const int HEARTBEAT_INTERVAL = 30000; // 30秒
public HeartbeatManager(ISocket socket)
{
_socket = socket;
_heartbeatTimer = new Timer(SendHeartbeat, null,
HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL);
}
private async void SendHeartbeat(object state)
{
if (_socket.IsConnected)
{
try
{
var heartbeat = Encoding.UTF8.GetBytes("PING");
await _socket.SendAsync(heartbeat);
}
catch (Exception ex)
{
// 心跳发送失败,可能连接已断开
Console.WriteLine($"心跳发送失败: {ex.Message}");
}
}
}
}
配置说明
基本配置
var client = new NewTcpClient(
serverIp: "192.168.1.100",
serverPort: 8080,
encoding: Encoding.UTF8,
messageMaxLength: 1024 * 1024 // 1MB
);
高级配置
var advancedClient = new NewTcpClient()
{
TryReConnect = true,
ReConnectPeriodMilliseconds = 5000,
MessageMaxLength = 1024 * 1024 * 10 // 10MB
};
依赖说明
- System.Net.Sockets: 核心Socket API
- System.Security.Cryptography: 加密相关功能
- IceTea.Pure: 基础工具类库
兼容性
- .NET版本: .NET Standard 2.0+
- 操作系统: Windows, Linux, macOS
- 协议支持: TCP, UDP, SSL/TLS
许可证
MIT License
作者
WuMing
贡献
欢迎提交 Issue 和 Pull Request!
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. 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 was computed. 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. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 is compatible. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.0
- IceTea.Pure (>= 1.2.22)
-
.NETStandard 2.1
- IceTea.Pure (>= 1.2.22)
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 |
|---|---|---|
| 2.0.9 | 115 | 3/4/2026 |
| 2.0.7 | 240 | 9/28/2025 |
| 2.0.6 | 168 | 8/23/2025 |
| 2.0.5 | 153 | 8/22/2025 |
| 2.0.4 | 142 | 8/2/2025 |
| 2.0.1 | 237 | 7/3/2025 |
| 2.0.0 | 268 | 4/22/2025 |
| 1.1.6 | 218 | 12/20/2024 |
| 1.1.5 | 222 | 12/8/2024 |
| 1.1.4 | 222 | 12/6/2024 |
| 1.1.3 | 232 | 9/29/2024 |
| 1.1.2 | 224 | 7/13/2024 |
| 1.1.1 | 254 | 4/24/2024 |
| 1.1.0 | 350 | 11/20/2023 |
| 1.0.6 | 224 | 11/17/2023 |
| 1.0.5 | 218 | 11/17/2023 |
| 1.0.4 | 226 | 11/17/2023 |
Loading failed