Liam.TcpServer
1.0.2
dotnet add package Liam.TcpServer --version 1.0.2
NuGet\Install-Package Liam.TcpServer -Version 1.0.2
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="Liam.TcpServer" Version="1.0.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Liam.TcpServer" Version="1.0.2" />
<PackageReference Include="Liam.TcpServer" />
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 Liam.TcpServer --version 1.0.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: Liam.TcpServer, 1.0.2"
#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 Liam.TcpServer@1.0.2
#: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=Liam.TcpServer&version=1.0.2
#tool nuget:?package=Liam.TcpServer&version=1.0.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
Liam.TcpServer
现代化TCP服务器通信库,支持多客户端连接管理、异步数据传输、SSL/TLS安全通信、心跳检测、连接池管理等功能,基于.NET 8.0构建。
功能特性
🚀 核心功能
- TCP服务器管理: 启动/停止服务器,端口绑定,多客户端连接管理
- 客户端连接处理: 连接建立/断开事件,连接状态监控,自动清理断开连接
- 数据传输: 同步/异步数据发送接收,支持字节数组、字符串、自定义协议
- 消息处理: 消息分包/粘包处理,心跳检测,超时管理
- 事件驱动架构: 客户端连接/断开事件,数据接收事件,错误处理事件
🔒 安全特性
- SSL/TLS支持: 安全的加密通信
- IP白名单/黑名单: 访问控制和安全防护
- 连接频率限制: 防止恶意连接攻击
- 认证机制: 支持多种认证方式
- 消息加密: 可选的消息级加密
⚡ 性能优化
- 异步I/O操作: 高性能的异步网络通信
- 连接池管理: 最大连接数限制,连接复用,资源优化
- 缓冲区管理: 智能的内存管理和缓冲区优化
- 内存池使用: 减少GC压力,提升性能
📊 监控统计
- 连接数统计: 实时连接数、历史峰值、连接成功率
- 数据传输量统计: 发送/接收字节数、消息数量
- 性能指标监控: 传输速率、错误率、响应时间
- 健康状态检查: 服务器健康状态监控
安装
dotnet add package Liam.TcpServer
快速开始
基本使用
using Liam.TcpServer.Extensions;
using Liam.TcpServer.Models;
// 配置服务
var services = new ServiceCollection();
services.AddTcpServer(config =>
{
config.Port = 8080;
config.MaxConnections = 1000;
config.EnableHeartbeat = true;
});
var serviceProvider = services.BuildServiceProvider();
var tcpServer = serviceProvider.GetRequiredService<ITcpServer>();
// 订阅事件
tcpServer.ClientConnected += (sender, e) =>
{
Console.WriteLine($"客户端已连接: {e.Connection.ClientIpAddress}");
};
tcpServer.DataReceived += (sender, e) =>
{
var message = Encoding.UTF8.GetString(e.Data);
Console.WriteLine($"收到消息: {message}");
// 回显消息
_ = tcpServer.SendTextAsync(e.Connection.Id, $"Echo: {message}");
};
// 启动服务器
await tcpServer.StartAsync();
Console.WriteLine("TCP服务器已启动,按任意键停止...");
Console.ReadKey();
// 停止服务器
await tcpServer.StopAsync();
SSL/TLS 安全通信
using System.Security.Cryptography.X509Certificates;
// 加载SSL证书
var certificate = new X509Certificate2("server.pfx", "password");
// 配置SSL服务器
services.AddSslTcpServer(certificate, 8443);
var tcpServer = serviceProvider.GetRequiredService<ITcpServer>();
await tcpServer.StartAsync();
安全配置
services.AddTcpServer(config =>
{
config.Port = 8080;
config.MaxConnections = 500;
})
.EnableTcpServerWhitelist("192.168.1.100", "192.168.1.101") // IP白名单
.EnableTcpServerRateLimit(60) // 每分钟最大60个连接
.EnableTcpServerAuthentication("my-secret-key"); // 启用认证
心跳检测
services.AddTcpServer(config =>
{
config.Port = 8080;
config.EnableHeartbeat = true;
config.HeartbeatIntervalSeconds = 30; // 30秒心跳间隔
config.HeartbeatTimeoutSeconds = 10; // 10秒超时
});
自定义消息处理
public class CustomMessageHandler : ICustomMessageHandler<MyMessage>
{
public byte MessageType => 0x10;
public async Task HandleAsync(ClientConnection connection, MyMessage message, CancellationToken cancellationToken)
{
// 处理自定义消息
Console.WriteLine($"处理自定义消息: {message.Content}");
}
public MyMessage? Deserialize(byte[] data)
{
// 反序列化逻辑
return JsonSerializer.Deserialize<MyMessage>(data);
}
public byte[] Serialize(MyMessage message)
{
// 序列化逻辑
return JsonSerializer.SerializeToUtf8Bytes(message);
}
}
// 注册自定义处理器
services.AddCustomMessageHandler<CustomMessageHandler, MyMessage>();
高级用法
广播消息
// 广播文本消息到所有客户端
await tcpServer.BroadcastTextAsync("Hello, everyone!");
// 广播JSON数据
await tcpServer.BroadcastJsonAsync(JsonSerializer.Serialize(new { Type = "Notification", Message = "System update" }));
// 发送到已认证的客户端
var data = Encoding.UTF8.GetBytes("Authenticated users only");
await tcpServer.SendToAuthenticatedAsync(data);
连接管理
// 获取所有连接
var allConnections = tcpServer.GetAllConnections();
// 获取活跃连接
var activeConnections = tcpServer.GetActiveConnections();
// 断开指定客户端
await tcpServer.DisconnectClientAsync(connectionId, "管理员断开");
// 清理断开的连接
await tcpServer.CleanupDisconnectedConnectionsAsync();
统计信息
// 获取服务器统计信息
var stats = tcpServer.GetStatistics();
Console.WriteLine($"当前连接数: {stats.CurrentConnections}");
Console.WriteLine($"总发送字节: {stats.TotalBytesSent}");
Console.WriteLine($"错误率: {stats.ErrorRate:P2}");
// 获取连接摘要
var summary = tcpServer.GetConnectionsSummary();
Console.WriteLine(summary);
// 健康状态检查
var health = tcpServer.CheckHealth();
Console.WriteLine($"服务器状态: {health.Status}");
文件传输
// 发送文件
await tcpServer.SendFileAsync(connectionId, "document.pdf");
// 发送流数据
using var fileStream = File.OpenRead("data.bin");
await tcpServer.SendStreamAsync(connectionId, fileStream);
配置选项
TcpServerConfig
public class TcpServerConfig
{
public int Port { get; set; } = 8080; // 监听端口
public IPAddress ListenAddress { get; set; } // 监听地址
public int MaxConnections { get; set; } = 1000; // 最大连接数
public int ReceiveBufferSize { get; set; } = 8192; // 接收缓冲区大小
public int SendBufferSize { get; set; } = 8192; // 发送缓冲区大小
public int ConnectionTimeoutSeconds { get; set; } = 30; // 连接超时时间
public bool EnableHeartbeat { get; set; } = true; // 启用心跳检测
public int HeartbeatIntervalSeconds { get; set; } = 60; // 心跳间隔
public bool EnableSsl { get; set; } = false; // 启用SSL
public X509Certificate2? SslCertificate { get; set; } // SSL证书
public SecuritySettings Security { get; set; } // 安全设置
}
SecuritySettings
public class SecuritySettings
{
public bool EnableWhitelist { get; set; } = false; // 启用IP白名单
public bool EnableBlacklist { get; set; } = false; // 启用IP黑名单
public bool EnableConnectionRateLimit { get; set; } = false; // 启用连接频率限制
public int ConnectionRateLimit { get; set; } = 60; // 连接频率限制
public bool EnableAuthentication { get; set; } = false; // 启用认证
public string? AuthenticationKey { get; set; } // 认证密钥
public bool EnableMessageEncryption { get; set; } = false; // 启用消息加密
}
事件处理
// 客户端连接事件
tcpServer.ClientConnected += (sender, e) =>
{
Console.WriteLine($"新客户端连接: {e.Connection.GetConnectionSummary()}");
};
// 客户端断开事件
tcpServer.ClientDisconnected += (sender, e) =>
{
Console.WriteLine($"客户端断开: {e.Connection.Id}, 原因: {e.Reason}");
};
// 数据接收事件
tcpServer.DataReceived += (sender, e) =>
{
Console.WriteLine($"收到数据: {e.Data.Length} 字节");
};
// 错误事件
tcpServer.Error += (sender, e) =>
{
Console.WriteLine($"发生错误: {e.Exception.Message}");
};
// 心跳事件
tcpServer.Heartbeat += (sender, e) =>
{
Console.WriteLine($"心跳{(e.IsRequest ? "请求" : "响应")}: {e.Connection.Id}");
};
依赖注入集成
// 在 Program.cs 中配置
builder.Services.AddTcpServer(config =>
{
config.Port = 8080;
config.MaxConnections = 1000;
config.EnableHeartbeat = true;
});
// 添加日志记录
builder.Services.AddTcpServerLogging();
// 在控制器或服务中使用
public class MyService
{
private readonly ITcpServer _tcpServer;
public MyService(ITcpServer tcpServer)
{
_tcpServer = tcpServer;
}
public async Task StartServerAsync()
{
await _tcpServer.StartAsync();
}
}
最佳实践
- 资源管理: 始终使用
using
语句或正确调用Dispose()
方法 - 异常处理: 订阅
Error
事件处理异常情况 - 连接限制: 根据服务器性能设置合适的最大连接数
- 心跳检测: 在不稳定网络环境中启用心跳检测
- 安全配置: 在生产环境中启用SSL和访问控制
- 监控统计: 定期检查服务器统计信息和健康状态
- 日志记录: 集成 Liam.Logging 进行详细的日志记录
性能建议
- 使用异步方法进行所有I/O操作
- 合理设置缓冲区大小以平衡内存使用和性能
- 在高并发场景下考虑使用连接池
- 定期清理断开的连接以释放资源
- 监控内存使用情况,避免内存泄漏
代码质量报告
质量检查结果 (2025-06-15)
总体评级:A+ (优秀) 🏆
检查项目 | 优先级 | 状态 | 检查结果 |
---|---|---|---|
安全性修复 | P0 | ✅ 通过 | SSL/TLS安全配置、无硬编码认证、输入验证完整、ConfigureAwait正确使用 |
编译器警告 | P1 | ✅ 通过 | 0个编译警告、可空引用类型完整、标准Dispose模式、异常处理完善 |
性能优化 | P2 | ✅ 通过 | 心跳并发控制(50个)、缓冲区优化、Memory<T>高效使用、字符串优化 |
代码质量 | P3 | ✅ 通过 | XML文档100%覆盖、常量集中化、66个测试全部通过、高测试覆盖率 |
安全特性亮点
- 🔐 现代加密:PBKDF2/Argon2密码哈希、AES-256-GCM消息加密
- 🔑 密钥管理:安全密钥生成、轮换机制、内存清理
- 🛡️ SSL/TLS:TLS 1.2/1.3支持、证书验证、握手超时控制
- 🚫 访问控制:IP白名单/黑名单、连接频率限制、认证机制
性能优化亮点
- ⚡ 异步I/O:真正的异步网络操作、ConfigureAwait(false)优化
- 🔄 并发控制:心跳发送并发限制、SemaphoreSlim流量控制
- 💾 内存优化:高效缓冲区管理、Memory<T>/Span<T>使用
- 📊 监控统计:实时性能指标、连接状态监控、健康检查
测试覆盖情况
- 测试用例:66个单元测试全部通过 ✅
- 测试框架:xUnit + Moq + FluentAssertions
- 覆盖范围:核心功能、异常处理、异步方法、Mock隔离
- 质量保证:持续集成、代码覆盖率报告
版本历史
版本 | 发布日期 | 主要变更 |
---|---|---|
1.0.1 | 2025-06-15 | 安全性增强:实现PBKDF2/Argon2密码哈希、AES-256-GCM消息加密、安全密钥轮换机制;性能优化:ArrayPool缓冲区管理、心跳并发控制、ConfigureAwait优化;代码质量:IAsyncDisposable支持、完整单元测试覆盖(66个测试)、常量集中化管理;P0-P3级全面修复:移除Task.Run反模式、SSL配置优化、异常处理优化、Memory<T>/Span<T>高效内存操作、XML文档完善 |
1.0.0 | 2025-06-15 | 初始版本,支持基础TCP服务器功能、SSL/TLS、心跳检测、安全控制 |
许可证
本项目采用 MIT 许可证。详情请参阅 LICENSE 文件。
相关项目
- Liam.Logging - 日志记录库
- Liam.Cryptography - 加密功能库
- Liam.SerialPort - 串口通讯库
Product | Versions 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 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. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- Liam.Logging (>= 1.1.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Hosting.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.1)
- Microsoft.Extensions.Options (>= 8.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.