C# WebSocket服务端 代码
时间: 2024-10-26 22:02:01 浏览: 23
在C#中,WebSocket服务端通常使用`System.Net.WebSockets命名空间`提供的类来实现。下面是一个简单的例子,展示了一个基础的WebSocket服务器:
```csharp
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core;
public class WebSocketServer
{
private readonly List<string> _clients = new List<string>();
public void Start()
{
var serverBuilder = WebHost.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel(options =>
{
options.Listen(5000, "localhost");
})
.UseStartup<Startup>();
});
using (var server = serverBuilder.Build())
{
server.Run();
}
}
public class Startup
{
// Configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseWebSockets((context) =>
{
context.WebSocket.OnOpen(async (sender, e) =>
{
_clients.Add(context.WebSocket.RemoteAddress.ToString());
await context.SendAsync($"Welcome! You are connected with ID {_clients.Count - 1}", WebSocketMessageType.Text, true);
});
context.WebSocket.OnClose(async (sender, e) =>
{
_clients.Remove(context.WebSocket.RemoteAddress.ToString());
await context.SendAsync($"Goodbye! User {e.CloseStatus} has disconnected", WebSocketMessageType.Text, true);
});
context.WebSocket.OnMessageAsync(async (sender, e) =>
{
foreach (var client in _clients)
{
await context.WebSocket.SendAsync(e.Data, WebSocketMessageType.Text, true, endOfMessage: false);
}
});
});
}
}
}
```
这个示例创建了一个WebSocket服务器监听本地的5000端口,当新的客户端连接时,它会发送欢迎信息,并处理消息广播。当用户断开连接时,会发送告别信息。
阅读全文