5 分钟快速上手 Cyaim.WebSocketServer。
dotnet add package Cyaim.WebSocketServerdotnet new web -n WebSocketServerApp
cd WebSocketServerAppdotnet add package Cyaim.WebSocketServerusing Cyaim.WebSocketServer.Infrastructure.Handlers.MvcHandler;
using Cyaim.WebSocketServer.Infrastructure.Configures;
var builder = WebApplication.CreateBuilder(args);
// 配置 WebSocket 路由
builder.Services.ConfigureWebSocketRoute(x =>
{
x.WebSocketChannels = new Dictionary<string, WebSocketRouteOption.WebSocketChannelHandler>()
{
{ "/ws", new MvcChannelHandler().ConnectionEntry }
};
x.ApplicationServiceCollection = builder.Services;
});
builder.Services.AddControllers();
var app = builder.Build();
app.UseWebSockets();
app.UseWebSocketServer();
app.MapControllers();
app.Run();using Cyaim.WebSocketServer.Infrastructure.Attributes;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class EchoController : ControllerBase
{
[WebSocket]
[HttpGet]
public string Echo(string message)
{
return $"Echo: {message}";
}
}dotnet run使用 WebSocket 客户端连接到 ws://localhost:5000/ws,发送:
{
"target": "Echo.Echo",
"body": {
"message": "Hello, WebSocket!"
}
}服务器可以向客户端主动发送数据:
using Cyaim.WebSocketServer.Infrastructure;
using Cyaim.WebSocketServer.Infrastructure.Attributes;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class MessageController : ControllerBase
{
[WebSocket]
[HttpGet]
public string SendMessage()
{
// 获取当前连接 ID
var connectionId = HttpContext.Connection.Id;
// 发送文本消息(使用扩展方法)
_ = "Hello from server!".SendTextAsync(connectionId);
return "Message sent";
}
[WebSocket]
[HttpGet]
public string SendNotification()
{
var connectionId = HttpContext.Connection.Id;
// 发送 JSON 对象
var notification = new
{
Type = "Notification",
Message = "You have a new message",
Timestamp = DateTime.UtcNow
};
_ = notification.SendJsonAsync(connectionId);
return "Notification sent";
}
}提示: 更多发送数据的方法和示例,请查看 向客户端发送数据 章节。