Cyaim.WebSocketServer
2.26.1021.1621
dotnet add package Cyaim.WebSocketServer --version 2.26.1021.1621
NuGet\Install-Package Cyaim.WebSocketServer -Version 2.26.1021.1621
<PackageReference Include="Cyaim.WebSocketServer" Version="2.26.1021.1621" />
<PackageVersion Include="Cyaim.WebSocketServer" Version="2.26.1021.1621" />
<PackageReference Include="Cyaim.WebSocketServer" />
paket add Cyaim.WebSocketServer --version 2.26.1021.1621
#r "nuget: Cyaim.WebSocketServer, 2.26.1021.1621"
#:package Cyaim.WebSocketServer@2.26.1021.1621
#addin nuget:?package=Cyaim.WebSocketServer&version=2.26.1021.1621
#tool nuget:?package=Cyaim.WebSocketServer&version=2.26.1021.1621
WebSocketServer
| 996ICU | Version | NuGet | Build | Code Size | License |
|---|---|---|---|---|---|
WebSocketServer is a lightweight and high-performance WebSocket library. Supports routing, full-duplex communication, clustering, and multi-language client SDKs.
📚 Documentation Center / 文档中心
- English Documentation - Complete English documentation
- 中文文档 - 完整的中文文档
✨ Features / 特性
- ✅ Lightweight & High Performance - Based on ASP.NET Core
- ✅ Routing System - MVC-like routing mechanism
- ✅ Full Duplex Communication - Bidirectional communication support
- ✅ Multi-node Cluster - Raft-based consensus protocol
- ✅ Multi-language Clients - C#, TypeScript, Rust, Java, Dart, Python
- ✅ Automatic Endpoint Discovery - Client SDKs auto-discover server endpoints
- ✅ Streaming Upload -
[WebSocket(Stream = true)]streams large files with constant server memory / 大文件流式上传,服务端内存恒定 - ✅ Receive Memory Control - Per-connection / per-endpoint / global receive caps, safe by default / 三级接收内存封顶,默认即安全
- ✅ Dashboard - Real-time monitoring and statistics
QuickStart
1. Install Library / 安装库
# Package Manager
Install-Package Cyaim.WebSocketServer
# .NET CLI
dotnet add package Cyaim.WebSocketServer
# PackageReference
<PackageReference Include="Cyaim.WebSocketServer" Version="2.0.0" />
2. Configure WebSocket Server / 配置 WebSocket 服务器
Using Minimal API / 使用 Minimal API
Two lines are all you need — AddWebSocketServer() automatically wires an MvcChannelHandler on channel /ws and discovers all [WebSocket] endpoints in your *.Controllers namespace.
只需两行代码 —— AddWebSocketServer() 会自动在 /ws 通道上挂载 MvcChannelHandler,并自动发现 *.Controllers 命名空间下所有标记了 [WebSocket] 的终结点。
using Cyaim.WebSocketServer.Infrastructure;
using Cyaim.WebSocketServer.Middlewares;
var builder = WebApplication.CreateBuilder(args);
// Add WebSocket server (default channel: /ws) / 添加 WebSocket 服务器(默认通道:/ws)
builder.Services.AddWebSocketServer();
var app = builder.Build();
app.UseWebSockets();
app.UseWebSocketServer();
app.Run();
Need more channels or options? Use the fluent builder or the configure overload:
需要更多通道或配置?使用流式构建器或配置重载:
// Custom channels / 自定义通道
builder.Services.AddWebSocketServer()
.AddMvcChannel("/im") // MVC-style channel / MVC 风格通道
.AddChannel("/chat", myHandler.ConnectionEntry); // Custom handler / 自定义处理器
// Note: explicitly adding channels replaces the auto default "/ws".
// 注意:显式添加通道会替换自动默认的 "/ws" 通道。
// Custom options / 自定义配置
builder.Services.AddWebSocketServer(x =>
{
x.MaxConnectionLimit = 10000;
x.WatchAssemblyNamespacePrefix = "MyApp.WsControllers"; // Endpoint scan prefix / 终结点扫描前缀
});
Using Startup.cs / 使用 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddWebSocketServer();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseWebSockets();
app.UseWebSocketServer();
}
Advanced: Manual Configuration / 高级:手动配置
ConfigureWebSocketRoute remains fully supported when you want full manual control (channel table, service collection, etc.):
当您需要完全手动控制(通道表、服务容器等)时,仍可使用 ConfigureWebSocketRoute:
using Cyaim.WebSocketServer.Infrastructure.Handlers.MvcHandler;
using Cyaim.WebSocketServer.Infrastructure.Configures;
using Cyaim.WebSocketServer.Middlewares;
var builder = WebApplication.CreateBuilder(args);
// Configure WebSocket route manually / 手动配置 WebSocket 路由
builder.Services.ConfigureWebSocketRoute(x =>
{
var mvcHandler = new MvcChannelHandler();
x.WebSocketChannels = new Dictionary<string, WebSocketRouteOption.WebSocketChannelHandler>()
{
{ "/ws", mvcHandler.ConnectionEntry }
};
x.ApplicationServiceCollection = builder.Services;
});
var app = builder.Build();
// Configure WebSocket options / 配置 WebSocket 选项
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
};
app.UseWebSockets(webSocketOptions);
app.UseWebSocketServer();
app.Run();
3. Mark WebSocket Endpoints / 标记 WebSocket 端点
Add [WebSocket] attribute to your controller actions:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[WebSocket] // Mark as WebSocket endpoint / 标记为 WebSocket 端点
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray();
}
}
Note: The
targetparameter in requests is case-insensitive.
注意: 请求中的target参数不区分大小写。
Request and Response
Scheme namespace 👇
Request Cyaim.WebSocketServer.Infrastructure.Handlers.MvcRequestScheme
Response Cyaim.WebSocketServer.Infrastructure.Handlers.MvcResponseScheme
Request target ignore case
Request scheme
1. Nonparametric method request
{
"target": "WeatherForecast.Get",
"body": {}
}
This request will be located at "WeatherForecastController" → "Get" Method.
Response to this request
{
"Target": "WeatherForecast.Get"
"Status": 0,
"Msg": null,
"RequestTime": 637395762382112345,
"CompleteTime": 637395762382134526,
"Body": [{
"Date": "2020-10-30T13:50:38.2133285+08:00",
"TemperatureC": 43,
"TemperatureF": 109,
"Summary": "Scorching"
}, {
"Date": "2020-10-31T13:50:38.213337+08:00",
"TemperatureC": 1,
"TemperatureF": 33,
"Summary": "Chilly"
}]
}
Forward invoke method return content will write MvcResponseScheme.Body.
2. Request with parameters
Example Code:
- Change method code to:
[WebSocket]
[HttpGet]
public IEnumerable<WeatherForecast> Get(Test a)
{
var rng = new Random();
return Enumerable.Range(1, 2).Select(index => new WeatherForecast
{
TemperatureC = a.PreTemperatureC + rng.Next(-20, 55),
Summary = a.PreSummary + Summaries[rng.Next(Summaries.Length)]
}).ToArray();
}
- Define parameter class
public class Test
{
public string PreSummary { get; set; }
public int PreTemperatureC { get; set; }
}
Request parameter
{
"target": "WeatherForecast.Get",
"body": {
"PreSummary":"Cyaim_",
"PreTemperatureC":233
}
}
Request body will be deserialized and passed to the method parameter.
Response to this request
{
"Target": "WeatherForecast.Get",
"Status": 0,
"Msg": null,
"RequestTime": 0,
"CompleteTime": 637395922139434966,
"Body": [{
"Date": "0001-01-01T00:00:00",
"TemperatureC": 282,
"TemperatureF": 539,
"Summary": "Cyaim_Warm"
}, {
"Date": "0001-01-01T00:00:00",
"TemperatureC": 285,
"TemperatureF": 544,
"Summary": "Cyaim_Sweltering"
}]
}
Client SDKs / 客户端 SDK
We provide multi-language client SDKs with automatic endpoint discovery:
- C# - Cyaim.WebSocketServer.Client
- TypeScript/JavaScript - @cyaim/websocket-client
- Rust - cyaim-websocket-client
- Java - websocket-client
- Dart - cyaim_websocket_client
- Python - cyaim-websocket-client
Quick Example / 快速示例
C# Client:
using Cyaim.WebSocketServer.Client;
var factory = new WebSocketClientFactory("http://localhost:5000", "/ws");
var client = await factory.CreateClientAsync<IWeatherService>();
var forecasts = await client.GetForecastsAsync();
TypeScript Client:
import { WebSocketClientFactory } from '@cyaim/websocket-client';
const factory = new WebSocketClientFactory('http://localhost:5000', '/ws');
const client = await factory.createClient<IWeatherService>({
getForecasts: async () => {}
});
const forecasts = await client.getForecasts();
For more details, see: Clients Documentation | 客户端文档
Streaming Upload & Memory Control / 流式上传与接收内存控制
Ordinary endpoints buffer each message (default cap 4 MiB, configurable via MaxRequestReceiveDataLimit
or per-endpoint [WebSocket(MaxBytes = N)]). To transfer large files, mark the endpoint Stream = true — the
payload is fed to your endpoint as a Stream without buffering, so server memory stays constant.
普通端点会整条缓冲消息(默认上限 4 MiB,可用 MaxRequestReceiveDataLimit 或端点级 [WebSocket(MaxBytes = N)] 调整)。要传大文件,把端点标成 Stream = true,负载会作为 Stream 边收边喂给端点,服务端内存恒定。
// Server: a streaming upload endpoint / 服务端:流式上传端点
[WebSocket("file.upload", Stream = true, MaxBytes = 2L * 1024 * 1024 * 1024)]
public async Task<object> Upload(UploadMeta meta, Stream body, CancellationToken ct)
{
await using var fs = File.Create(Path.Combine(dir, meta.FileName));
await body.CopyToAsync(fs, ct); // constant memory, end-to-end backpressure
return new { bytes = fs.Length };
}
// Client: upload with the uploadStream helper (all 6 SDKs provide one) / 客户端:uploadStream 帮助方法
const res = await client.uploadStream("file.upload", fs.createReadStream("big.bin"), { fileName: "big.bin" });
⚠️ 2.0 behaviour change:
MaxRequestReceiveDataLimitnow defaults to 4 MiB (was unlimited). If you send single messages larger than 4 MiB through ordinary endpoints, raise it (or setnull), or use a streaming endpoint. / 2.0 行为变更:该上限默认从"不限"改为 4 MiB,大消息需显式调大或改用流式端点。
For more details, see: Streaming Upload & Memory Control | 流式上传与内存控制
Cluster / 集群
Cyaim.WebSocketServer supports multi-node clustering with Raft consensus protocol. You can use WebSocket, Redis, or RabbitMQ for inter-node communication.
Basic Cluster Setup / 基础集群配置
using Cyaim.WebSocketServer.Infrastructure.Cluster;
using Cyaim.WebSocketServer.Infrastructure.Configures;
var builder = WebApplication.CreateBuilder(args);
// Configure WebSocket route / 配置 WebSocket 路由
builder.Services.ConfigureWebSocketRoute(x =>
{
var mvcHandler = new MvcChannelHandler();
x.WebSocketChannels = new Dictionary<string, WebSocketRouteOption.WebSocketChannelHandler>()
{
{ "/ws", mvcHandler.ConnectionEntry }
};
x.ApplicationServiceCollection = builder.Services;
});
var app = builder.Build();
// Configure WebSocket / 配置 WebSocket
app.UseWebSockets();
app.UseWebSocketServer(serviceProvider =>
{
// Configure cluster / 配置集群
var clusterOption = new ClusterOption
{
NodeId = "node1",
NodeAddress = "localhost",
NodePort = 5000,
TransportType = "ws", // or "redis" or "rabbitmq"
ChannelName = "/cluster",
Nodes = new[]
{
"ws://localhost:5001/node2",
"ws://localhost:5002/node3"
}
};
return clusterOption;
});
app.Run();
Using Redis Transport / 使用 Redis 传输
# Install Redis transport package / 安装 Redis 传输包
dotnet add package Cyaim.WebSocketServer.Cluster.StackExchangeRedis
var clusterOption = new ClusterOption
{
NodeId = "node1",
TransportType = "redis",
RedisConnectionString = "localhost:6379",
ChannelName = "/cluster",
Nodes = new[] { "node1", "node2", "node3" }
};
Using RabbitMQ Transport / 使用 RabbitMQ 传输
# Install RabbitMQ transport package / 安装 RabbitMQ 传输包
dotnet add package Cyaim.WebSocketServer.Cluster.RabbitMQ
var clusterOption = new ClusterOption
{
NodeId = "node1",
TransportType = "rabbitmq",
RabbitMQConnectionString = "amqp://guest:guest@localhost:5672/",
ChannelName = "/cluster",
Nodes = new[] { "node1", "node2", "node3" }
};
For more details, see: Cluster Documentation | 集群文档
📖 More Documentation / 更多文档
- Quick Start Guide - Get started in 5 minutes / 5 分钟快速上手
- Core Library - Core features and routing / 核心功能和路由
- Streaming Upload & Memory Control - Large-file streaming upload & receive caps / 大文件流式上传与接收内存控制
- Configuration Guide - Configuration options / 配置选项
- API Reference - Complete API documentation / 完整 API 文档
- Dashboard - Monitoring and statistics / 监控和统计
- Metrics - OpenTelemetry integration / OpenTelemetry 集成
- Hybrid Cluster Transport - Redis + RabbitMQ hybrid transport / Redis + RabbitMQ 混合传输
🔗 Related Links / 相关链接
📄 License / 许可证
This project is licensed under the Apache License 2.0.
本项目基于 Apache License 2.0 开源。
Copyright © Cyaim Studio
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 is compatible. 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 is compatible. 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 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 is compatible. 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 | netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.1 is compatible. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.1
- Microsoft.AspNetCore.Hosting.Server.Abstractions (>= 2.3.0)
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.0)
- Microsoft.CSharp (>= 4.7.0)
- Microsoft.Extensions.Configuration.Binder (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Hosting.Abstractions (>= 9.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 9.0.0)
- Microsoft.Extensions.ObjectPool (>= 9.0.0)
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
- System.Text.Json (>= 10.0.2)
- System.Threading.Channels (>= 10.0.2)
-
net10.0
- No dependencies.
-
net6.0
- Microsoft.Extensions.Configuration.Binder (>= 8.0.1)
- Microsoft.Extensions.ObjectPool (>= 8.0.11)
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
-
net7.0
- Microsoft.Extensions.Configuration.Binder (>= 8.0.1)
- Microsoft.Extensions.ObjectPool (>= 8.0.11)
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages (7)
Showing the top 5 NuGet packages that depend on Cyaim.WebSocketServer:
| Package | Downloads |
|---|---|
|
Cyaim.WebSocketServer.Cluster.Hybrid
WebSocketServer Hybrid cluster transport extension (Redis for service discovery, RabbitMQ for message routing) WebSocketServer 混合集群传输扩展(Redis 用于服务发现,RabbitMQ 用于消息路由) Supports different Redis and RabbitMQ libraries through abstraction layer 通过抽象层支持不同的 Redis 和 RabbitMQ 库 |
|
|
Cyaim.WebSocketServer.MessagePack
WebSocketServer MessagePack binary protocol extension WebSocketServer MessagePack 二进制协议扩展 |
|
|
Cyaim.WebSocketServer.Cluster.FreeRedis
WebSocketServer FreeRedis cluster transport extension WebSocketServer FreeRedis 集群传输扩展 |
|
|
Cyaim.WebSocketServer.Cluster.RabbitMQ
WebSocketServer RabbitMQ cluster transport extension WebSocketServer RabbitMQ 集群传输扩展 |
|
|
Cyaim.WebSocketServer.Dashboard
WebSocketServer Dashboard for monitoring and managing WebSocket server and cluster WebSocketServer 仪表板,用于监控和管�?WebSocket 服务器和集群 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated | |
|---|---|---|---|
| 2.26.1021.1621 | 130 | 10/21/2026 | |
| 2.26.1021.1015 | 195 | 10/21/2026 | |
| 2.25.1205.1023 | 609 | 12/5/2025 | |
| 2.25.1205.945 | 542 | 12/5/2025 | |
| 2.25.1205.901 | 541 | 12/5/2025 | |
| 2.25.1205.706 | 548 | 12/5/2025 | |
| 2.25.1205.558 | 547 | 12/5/2025 | |
| 2.25.1205.525 | 537 | 12/5/2025 | |
| 2.25.1204.141 | 546 | 12/4/2025 | |
| 2.25.1203.534 | 1,022 | 12/3/2025 | |
| 2.25.1202.1527 | 1,020 | 12/2/2025 | |
| 2.25.1202.1149 | 1,022 | 12/2/2025 | |
| 2.25.1202.716 | 1,053 | 12/2/2025 | |
| 2.25.1201.1539 | 849 | 12/1/2025 | |
| 1.7.8 | 1,135 | 10/20/2024 | |
| 1.7.7 | 220 | 10/16/2024 | |
| 1.7.6 | 188 | 10/16/2024 | |
| 1.7.5 | 187 | 10/14/2024 | |
| 1.7.4 | 199 | 10/14/2024 | |
| 1.7.3 | 586 | 8/22/2024 |
## Version 2.0.0 - Major Release
### 🎉 New Features
- **Request ID Validation**: Added `RequireRequestId` configuration option (default: true) to reject requests without Id property, ensuring clients can distinguish response sources
- **Bandwidth Limiting**: Comprehensive bandwidth rate limiting system with channel-level and endpoint-level policies
- **Cluster Support**: Full cluster functionality with Raft protocol, automatic routing, and fault tolerance
- **Dashboard**: Complete monitoring dashboard with real-time statistics, bandwidth monitoring, and cluster management
- **Source Generator**: Performance-optimized source generator for endpoint injection and method invocation
- **OpenTelemetry Integration**: Standard metrics export support for observability
- **Access Control**: IP-based access control with configurable policies
### ⚡ Performance Improvements
- Optimized endpoint injection using source generators (fallback to reflection)
- Optimized method invocation using source generators (fallback to reflection)
- Improved connection management and resource cleanup
- Enhanced pipeline processing performance
### 🔧 Enhancements
- Enhanced error handling and logging
- Improved cluster connection registration and unregistration
- Better support for .NET 9.0 and .NET 10.0
- Enhanced metrics collection and statistics recording
### 📦 Cluster Extensions
- **StackExchange.Redis**: Redis cluster transport using StackExchange.Redis
- **FreeRedis**: Redis cluster transport using FreeRedis
- **RabbitMQ**: RabbitMQ cluster transport
- **Hybrid**: Hybrid cluster transport with Redis for service discovery and RabbitMQ for message routing
### 🐛 Bug Fixes
- Fixed Task return type handling for endpoint methods
- Fixed source generator injector type lookup logic
- Improved exception handling and error messages
- Fixed connection cleanup in cluster scenarios
### 📚 Documentation
- Updated documentation with new features
- Added bandwidth limiting configuration guide
- Enhanced cluster setup documentation
- Improved API reference documentation