AcceleratorSession 1.0.3

dotnet add package AcceleratorSession --version 1.0.3
                    
NuGet\Install-Package AcceleratorSession -Version 1.0.3
                    
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="AcceleratorSession" Version="1.0.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AcceleratorSession" Version="1.0.3" />
                    
Directory.Packages.props
<PackageReference Include="AcceleratorSession" />
                    
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 AcceleratorSession --version 1.0.3
                    
#r "nuget: AcceleratorSession, 1.0.3"
                    
#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 AcceleratorSession@1.0.3
                    
#: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=AcceleratorSession&version=1.0.3
                    
Install as a Cake Addin
#tool nuget:?package=AcceleratorSession&version=1.0.3
                    
Install as a Cake Tool

AcceleratorSession

AcceleratorSession 是一个高性能的 .NET 会话管理库,专门用于处理 WebSocket 和 Socket 连接。它提供了完整的会话生命周期管理、消息收发、空闲检测等功能。

特性

  • 支持 WebSocket 和 Socket 连接
  • 异步高性能 IO
  • 自动空闲会话检测和清理
  • 支持文本和二进制消息
  • 可扩展的消息编解码器
  • 完整的会话生命周期管理
  • 支持点对点消息和广播
  • 基于 Channel 的消息队列
  • 内存池优化
  • 完整的日志支持
  • 依赖注入支持

项目结构

AcceleratorSession/ ├── Abstractions/ │ ├── IAcceleratorSession.cs # 会话接口 │ ├── IMessageDecoder.cs # 消息解码器接口 │ ├── INetworkConnection.cs # 网络连接接口 │ └── ISessionManager.cs # 会话管理器接口 ├── Configuration/ │ └── AcceleratorSessionOptions.cs # 配置选项 ├── Connections/ │ └── WebSocketConnection.cs # WebSocket 连接实现 ├── Core/ │ ├── AcceleratorSession.cs # 会话基类 │ └── SessionManager.cs # 会话管理器实现 └── Extensions/ └── ServiceCollectionExtensions.cs # DI 扩展

快速开始

1. 安装

bash dotnet add package AcceleratorSession

2. 配置服务

csharp var builder = WebApplication.CreateBuilder(args); // 添加 WebSocket 支持 builder.Services.AddWebSockets(options ⇒ { options.KeepAliveInterval = TimeSpan.FromMinutes(2); }); // 配置会话管理器 builder.Services.AddAcceleratorSession(options ⇒ { options.IdleTimeout = TimeSpan.FromMinutes(5); options.MaxConcurrentSessions = 1000; options.BufferSize = 4096; }); // 添加自定义消息解码器 builder.Services.AddSingleton<IMessageDecoder, YourMessageDecoder>();

3. 实现消息解码器

csharp public class JsonMessageDecoder : IMessageDecoder { private readonly JsonSerializerOptions options; public JsonMessageDecoder() { options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; } public ValueTask<object?> DecodeAsync(ReadOnlyMemory<byte> message, Type targetType, CancellationToken cancellationToken = default) { var json = Encoding.UTF8.GetString(message.Span); return ValueTask.FromResult(JsonSerializer.Deserialize(json, targetType, options)); } public ValueTask<ReadOnlyMemory<byte>> EncodeAsync(object message, CancellationToken cancellationToken = default) { var json = JsonSerializer.Serialize(message, options); return ValueTask.FromResult<ReadOnlyMemory<byte>>(Encoding.UTF8.GetBytes(json)); } }

4. 创建自定义会话类

csharp public class YourSession : AcceleratorSession { private readonly IMessageDecoder messageDecoder; private readonly ISessionManager sessionManager; public YourSession( INetworkConnection connection, IMessageDecoder messageDecoder, ISessionManager sessionManager, ILogger<YourSession> logger, IOptions<AcceleratorSessionOptions> options) : base(connection, logger, options) { messageDecoder = messageDecoder; sessionManager = sessionManager; } protected override async ValueTask OnMessageReceived(ReadOnlyMemory<byte> message, MessageType messageType, CancellationToken cancellationToken) { await base.OnMessageReceived(message, messageType, cancellationToken); try { var yourMessage = await messageDecoder.DecodeAsync(message, typeof(YourMessageType), cancellationToken); await HandleMessageAsync(yourMessage as YourMessageType); } catch (Exception ex) { Logger.LogError(ex, "Error processing message"); } } }

5. 使用会话管理器

csharp // 获取指定会话 var session = sessionManager.GetSession("session-id"); // 获取所有会话 var sessions = sessionManager.GetAllSessions(); // 检查会话是否存在 bool exists = sessionManager.IsSessionExists("session-id"); // 发送消息到指定会话 await sessionManager.SendToSessionAsync("session-id", messageBytes, MessageType.Text); // 广播消息 await sessionManager.BroadcastMessageAsync("source-id", messageBytes, MessageType.Text); // 发送消息到多个会话 var targetIds = new[] { "session-1", "session-2" }; await sessionManager.SendToSessionsAsync(targetIds, messageBytes, MessageType.Text);

性能优化

  1. 内存池使用

    • 使用 MemoryPool<byte> 减少内存分配
    • 适当配置 BufferSize 以优化内存使用
  2. 消息队列

    • 使用 Channel 实现高效的消息队列
    • 单读多写模式保证消息顺序
  3. 异步IO

    • 全异步操作
    • 使用 ValueTask 减少分配
  4. 配置建议

    • 根据实际需求调整 IdleTimeout
    • 合理设置 MaxConcurrentSessions
    • 适当的 BufferSize 大小

注意事项

  1. 会话ID必须唯一
  2. 正确处理异常情况
  3. 及时清理不活跃的会话
  4. 注意消息大小限制
  5. 正确使用 CancellationToken
  6. 确保正确释放资源

高级功能

  1. 自定义消息编解码
  2. 会话生命周期管理
  3. 空闲检测和自动断开
  4. 消息广播和点对点发送
  5. 连接状态监控
  6. 完整的日志记录

许可证

MIT

贡献

欢迎提交 Issue 和 Pull Request

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 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.

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
1.0.3 305 11/19/2024
1.0.2 144 11/18/2024
1.0.1 162 11/17/2024
1.0.0 154 11/17/2024