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