This commit is contained in:
KP9lKk 2025-03-14 16:17:41 +03:00
parent 0f56c6a206
commit cda7524898

View File

@ -1,12 +1,37 @@
using System.Net.WebSockets;
using Microsoft.AspNetCore.Mvc;
namespace WebSocketsChatApi.Controllers;
[ApiController]
public class WebSocketChatController: ControllerBase
{
private static List<WebSocket> _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<Byte> buffer = new ArraySegment<byte>(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);
}
}
}
}