.NET实现WebSocket服务端即时通信实例
时间: 2023-12-10 12:15:39 浏览: 151
好的,以下是一个简单的.NET WebSocket服务端即时通信实例,供您参考:
1. 首先,创建一个空的ASP.NET Web应用程序。
2. 在项目中添加一个类文件,命名为WebSocketHandler.cs,并在其中添加以下代码:
```csharp
using System;
using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketServer
{
public class WebSocketHandler
{
private static ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();
public async Task Handle(WebSocket socket)
{
var socketId = Guid.NewGuid().ToString();
_sockets.TryAdd(socketId, socket);
while (socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(new byte[4096]);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
var message = System.Text.Encoding.UTF8.GetString(buffer.Array, buffer.Offset, result.Count);
await SendMessageToAllAsync(message);
}
else if (result.MessageType == WebSocketMessageType.Close)
{
WebSocket removedSocket;
_sockets.TryRemove(socketId, out removedSocket);
await removedSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
}
private static async Task SendMessageToAllAsync(string message)
{
foreach (var socket in _sockets)
{
if (socket.Value.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(message));
await socket.Value.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
}
```
3. 在项目中添加一个WebSocketMiddleware.cs类文件,并在其中添加以下代码:
```csharp
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace WebSocketServer
{
public class WebSocketMiddleware
{
private readonly RequestDelegate _next;
private WebSocketHandler _webSocketHandler { get; set; }
public WebSocketMiddleware(RequestDelegate next, WebSocketHandler webSocketHandler)
{
_next = next;
_webSocketHandler = webSocketHandler;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest)
{
await _next(context);
return;
}
var socket = await context.WebSockets.AcceptWebSocketAsync();
await _webSocketHandler.Handle(socket);
}
}
}
```
4. 在Startup.cs文件中添加以下代码:
```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace WebSocketServer
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddWebSocketManager();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseWebSockets();
app.MapWebSocketManager("/ws", app.ApplicationServices.GetService<WebSocketHandler>());
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
```
5. 在项目中添加一个WebSocketExtensions.cs文件,并在其中添加以下代码:
```csharp
using Microsoft.AspNetCore.Builder;
namespace WebSocketServer
{
public static class WebSocketExtensions
{
public static IApplicationBuilder MapWebSocketManager(this IApplicationBuilder app, string path, WebSocketHandler handler)
{
return app.Map(path, (x) => x.UseMiddleware<WebSocketMiddleware>(handler));
}
}
}
```
6. 在项目中添加一个WebSocketManagerExtensions.cs文件,并在其中添加以下代码:
```csharp
using Microsoft.Extensions.DependencyInjection;
namespace WebSocketServer
{
public static class WebSocketManagerExtensions
{
public static IServiceCollection AddWebSocketManager(this IServiceCollection services)
{
services.AddSingleton<WebSocketHandler>();
return services;
}
}
}
```
7. 运行应用程序,并使用WebSocket客户端连接到ws://localhost:5000/ws。您可以使用任何WebSocket客户端,如Chrome的WebSocket插件。
8. 您现在可以向服务器发送消息,并通过服务器将它们广播到所有连接的客户端。
希望这个例子能帮助到你!
阅读全文