From cda7524898d591dbb57588609997d28fd1d8ad58 Mon Sep 17 00:00:00 2001 From: KP9lKk Date: Fri, 14 Mar 2025 16:17:41 +0300 Subject: [PATCH] finally --- .../Controllers/WebSocketChatController.cs | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/WebSocketsChatApi/Controllers/WebSocketChatController.cs b/WebSocketsChatApi/Controllers/WebSocketChatController.cs index f9b5649..cc31c79 100644 --- a/WebSocketsChatApi/Controllers/WebSocketChatController.cs +++ b/WebSocketsChatApi/Controllers/WebSocketChatController.cs @@ -1,12 +1,37 @@ +using System.Net.WebSockets; using Microsoft.AspNetCore.Mvc; namespace WebSocketsChatApi.Controllers; [ApiController] public class WebSocketChatController: ControllerBase { + private static List _webSockets = new(); [Route("/chat")] public async Task Chat() { - + if (HttpContext.WebSockets.IsWebSocketRequest) + { + using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); + _webSockets.Add(webSocket); + await ResendMessages(webSocket); + } + else + { + HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; + } + } + + public async Task ResendMessages(WebSocket senderWebSocket) + { + while (senderWebSocket.State == WebSocketState.Open) + { + ArraySegment buffer = new ArraySegment(new Byte[1024 * 4]); + var result = await senderWebSocket.ReceiveAsync(buffer, CancellationToken.None); + foreach (var websocket in _webSockets) + { + if(senderWebSocket == websocket) continue; + await websocket.SendAsync(buffer.Array, WebSocketMessageType.Text, true, CancellationToken.None); + } + } } } \ No newline at end of file