C#C
C#2y ago
Alex

Only response web socket

How to create web socket that doesn't accept any messages, but clients can connect to it and listen for updates? If I don't create while loop, the client immediately disconnects.
if (HttpContext.WebSockets.IsWebSocketRequest)
{

    using WebSocket ws = await HttpContext.WebSockets.AcceptWebSocketAsync();

    string key = _socketManagerService.AddSocket(ws);

    await _socketManagerService.SendAsync(key,new WebSocketMessage
    {
        MessageType = MessageType.ConnectionEvent,
        Data = new WebSocketMessageData
        {
            Topic = "Connection",
            Payload = $"Connection established {DateTime.UtcNow}"
        }
    });

    _logger.LogInformation($"New connection: {key} {DateTime.UtcNow}");

    while (!HttpContext.RequestAborted.IsCancellationRequested)
    {
        
    }

    await _socketManagerService.RemoveSocketAsync(key);
}
Was this page helpful?