来一段.net 6 Websocket 聊天功能代码,并且附带.net core客户端代码
时间: 2024-02-19 15:02:36 浏览: 112
好的,下面是一个简单的使用 .NET 6 的 WebSocket 实现聊天室功能的代码示例:
服务端代码:
``` csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class ChatRoom
{
private readonly ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();
private readonly ILogger<ChatRoom> _logger;
public ChatRoom(ILogger<ChatRoom> logger)
{
_logger = logger;
}
public async Task HandleWebSocketAsync(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest)
{
context.Response.StatusCode = 400;
return;
}
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
string socketId = Guid.NewGuid().ToString();
_sockets.TryAdd(socketId, webSocket);
_logger.LogInformation($"WebSocket {socketId} connected");
try
{
await HandleIncomingMessageAsync(webSocket, socketId);
}
finally
{
_sockets.TryRemove(socketId, out _);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "WebSocket closed", CancellationToken.None);
_logger.LogInformation($"WebSocket {socketId} disconnected");
}
}
private async Task HandleIncomingMessageAsync(WebSocket webSocket, string socketId)
{
byte[] buffer = new byte[1024 * 4];
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
_logger.LogInformation($"WebSocket {socketId} received message: {message}");
await BroadcastMessageAsync(message, socketId);
}
}
private async Task BroadcastMessageAsync(string message, string excludeSocketId)
{
foreach (KeyValuePair<string, WebSocket> pair in _sockets)
{
if (pair.Key != excludeSocketId && pair.Value.State == WebSocketState.Open)
{
await pair.Value.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}
public static class ChatRoomExtensions
{
public static IApplicationBuilder UseChatRoom(this IApplicationBuilder app)
{
return app.Use(async (context, next) =>
{
if (context.Request.Path == "/chat")
{
ChatRoom chatRoom = context.RequestServices.GetService(typeof(ChatRoom)) as ChatRoom;
await chatRoom.HandleWebSocketAsync(context);
}
else
{
await next();
}
});
}
}
```
客户端代码:
``` csharp
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class ChatClient : IDisposable
{
private readonly ClientWebSocket _webSocket = new ClientWebSocket();
public async Task ConnectAsync(Uri uri)
{
await _webSocket.ConnectAsync(uri, CancellationToken.None);
Console.WriteLine("Connected to WebSocket server");
Task receiveTask = ReceiveAsync();
while (_webSocket.State == WebSocketState.Open)
{
string message = Console.ReadLine();
byte[] buffer = Encoding.UTF8.GetBytes(message);
await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
}
await receiveTask;
}
private async Task ReceiveAsync()
{
byte[] buffer = new byte[1024 * 4];
while (_webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine(message);
}
}
public async Task DisconnectAsync()
{
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "WebSocket closed", CancellationToken.None);
Console.WriteLine("Disconnected from WebSocket server");
}
public void Dispose()
{
_webSocket.Dispose();
}
}
```
使用方法:
在 ASP.NET Core 应用程序的 `Startup.cs` 文件中调用 `UseChatRoom()` 扩展方法,将 `/chat` 路径映射到 `ChatRoom` 类:
``` csharp
app.UseChatRoom();
```
在客户端代码中创建 `ChatClient` 实例,然后调用 `ConnectAsync()` 方法连接到 WebSocket 服务器:
``` csharp
ChatClient client = new ChatClient();
await client.ConnectAsync(new Uri("ws://localhost:5000/chat"));
```
当用户在控制台中输入文本时,调用 `SendAsync()` 方法将文本发送到服务器:
``` csharp
string message = Console.ReadLine();
await client.SendAsync(message);
```
当用户想要断开连接时,调用 `DisconnectAsync()` 方法断开连接:
``` csharp
await client.DisconnectAsync();
```
阅读全文