Cyaim.WebSocketServer 2.25.1205.1023

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

WebSocketServer

996ICU Version NuGet Build Code Size License
996.icu alternate text is missing from this package README imagealternate text is missing from this package README image alternate text is missing from this package README imageNuGet alternate text is missing from this package README image Code size LicenseLICENSE

WebSocketServer is a lightweight and high-performance WebSocket library. Supports routing, full-duplex communication, clustering, and multi-language client SDKs.

📚 Documentation Center / 文档中心

✨ 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
  • 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="1.7.8" />

2. Configure WebSocket Server / 配置 WebSocket 服务器

Using Minimal API / 使用 Minimal API

using Cyaim.WebSocketServer.Infrastructure.Handlers.MvcHandler;
using Cyaim.WebSocketServer.Middlewares;

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 options / 配置 WebSocket 选项
var webSocketOptions = new WebSocketOptions()
{
    KeepAliveInterval = TimeSpan.FromSeconds(120),
};
app.UseWebSockets(webSocketOptions);
app.UseWebSocketServer();

app.Run();

Using Startup.cs / 使用 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.ConfigureWebSocketRoute(x =>
    {
        var mvcHandler = new MvcChannelHandler();
        x.WebSocketChannels = new Dictionary<string, WebSocketRouteOption.WebSocketChannelHandler>()
        {
            { "/ws", mvcHandler.ConnectionEntry }
        };
        x.ApplicationServiceCollection = services;
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    var webSocketOptions = new WebSocketOptions()
    {
        KeepAliveInterval = TimeSpan.FromSeconds(120),
    };
    app.UseWebSockets(webSocketOptions);
    app.UseWebSocketServer();
}

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 target parameter 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:

  1. 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();
}
  1. 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:

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 | 客户端文档

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 / 更多文档

📄 License / 许可证

This project is licensed under MIT License.

Copyright © Cyaim Studio

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

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

WebSocketServer Dashboard for monitoring and managing WebSocket server and cluster WebSocketServer 仪表板,用于监控和管�?WebSocket 服务器和集群

Cyaim.WebSocketServer.Cluster.RabbitMQ

WebSocketServer RabbitMQ cluster transport extension WebSocketServer RabbitMQ 集群传输扩展

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.25.1205.1023 474 12/5/2025
2.25.1205.945 481 12/5/2025
2.25.1205.901 485 12/5/2025
2.25.1205.706 486 12/5/2025
2.25.1205.558 489 12/5/2025
2.25.1205.525 478 12/5/2025
2.25.1204.141 495 12/4/2025
2.25.1203.534 962 12/3/2025
2.25.1202.1527 964 12/2/2025
2.25.1202.1149 968 12/2/2025
2.25.1202.716 995 12/2/2025
2.25.1201.1539 797 12/1/2025
1.7.8 1,075 10/20/2024
1.7.7 175 10/16/2024
1.7.6 141 10/16/2024
1.7.5 141 10/14/2024
1.7.4 155 10/14/2024 1.7.4 is deprecated because it has critical bugs.
1.7.3 534 8/22/2024 1.7.3 is deprecated because it has critical bugs.
1.7.2 206 8/16/2024 1.7.2 is deprecated because it has critical bugs.
1.7.1 175 5/31/2024
1.7.0 178 5/30/2024 1.7.0 is deprecated because it has critical bugs.
1.6.4 151 5/21/2024
1.6.3 155 5/16/2024
1.6.2 159 5/15/2024 1.6.2 is deprecated because it is no longer maintained and has critical bugs.
1.6.1 180 5/15/2024 1.6.1 is deprecated because it has critical bugs.
1.6.0 432 11/25/2022
1.5.9 433 11/20/2022
1.5.8 603 12/30/2020
1.5.7 571 12/25/2020
1.5.6 513 12/3/2020
1.5.5 517 11/12/2020
1.5.4 547 11/12/2020
1.5.3 559 11/11/2020
1.5.2 543 11/10/2020
1.5.1 594 10/30/2020
1.5.0 593 10/30/2020
1.0.0 550 10/29/2020

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