在C#中,你可以使用System.Net.WebSockets
命名空间中的WebSocket
类来创建一个WebSocket服务器。以下是一个简单的示例,展示了如何创建一个WebSocket服务器并在接收到客户端连接时发送消息:
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace WebSocketServer
{
public class WebSocketHandler
{
private readonly WebSocket _webSocket;
public WebSocketHandler(WebSocket webSocket)
{
_webSocket = webSocket;
}
public async Task OnConnectedAsync()
{
// 接收客户端发送的消息
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result;
do
{
result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received message: {message}");
} while (!result.CloseStatus.HasValue);
// 向客户端发送消息
var responseMessage = "Hello from WebSocket server!";
var responseBuffer = Encoding.UTF8.GetBytes(responseMessage);
await _webSocket.SendAsync(new ArraySegment<byte>(responseBuffer), result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// 注册WebSocket路由
app.Map("/ws", async (HttpContext context) =>
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
var webSocketHandler = new WebSocketHandler(webSocket);
await webSocketHandler.OnConnectedAsync();
}
else
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("This endpoint only supports WebSocket connections.");
}
});
app.Run();
}
}
}
在这个示例中,我们创建了一个简单的HTTP服务器,监听/ws
路径上的WebSocket连接。当客户端连接到服务器时,OnConnectedAsync
方法会被调用。在这个方法中,我们首先接收客户端发送的消息,然后向客户端发送一条响应消息。