C#C
C#2y ago
Alex

Web sockets management

Hello! I don't understand how to hold a connection with client and how to detect when it was closed by client and remove it from list. I have route where users can subscribe to notification
/notifications/sub
. There I accept web socket and add it to dictionary, id is assigned to each web socket. Then I do the "while" loop because otherwise the connection closes immediately. Also I have a problem that if I close browsers is not removed from dictionary that I use to send messages? Is there a way to solve these problems?
[HttpGet("sub")]
public async Task Subscribe() {
  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 (ws.State == WebSocketState.Open) {
    }
    await _socketManagerService.RemoveSocketAsync(key);
    _logger.LogInformation($"Connection closed {key} - {DateTime.UtcNow}");
    // var socketFinishedTcs = new TaskCompletionSource<object>();
    // await socketFinishedTcs.Task;
  } else {
    throw new BadRequestException("Only web socket connections");
  }
}
Was this page helpful?
Web sockets management - C#