© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
48 replies
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
/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");
  }
}
[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");
  }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ winform sockets
C#CC# / help
2y ago
❔ Sockets - TCP
C#CC# / help
4y ago
Sockets and WPF
C#CC# / help
2y ago
❔ Problem with Sockets
C#CC# / help
3y ago