title: Handling closed websocket connection in asp.net core server
body: <p>Can anyone explain me how to remove websockets from clients that terminates their connection unexpectedly?
  I mean that the user closes the application in a bad way, without telling the server that they want to disconnect?
  And how generally you handle disconnection.</p>
  
  <p>I tried one piece of code that listen for message receive and has a cancellationTokenSource with 3s, so it will check if the connection is still alive. When I close the websocket client application the server do not go to the WebSocketState.Closed part, and when the cancellation token is triggered, the server drops my connection to client. I am doing something wrong here ?!
  Thanks in advance! </p>
  
  <pre><code>while (socket.State == WebSocketState.Open)
  {
     var cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(3000));
     buffer = new ArraySegment&lt;byte&gt;(new byte[4096]);
  
     WebSocketReceiveResult received = null;
  
  
     try
     {
         received = await socket.ReceiveAsync(buffer, cancellationSource);
     }
     catch (AggregateException e)
     {
         continue;
     }
  
     switch (received.MessageType)
     {
         case WebSocketMessageType.Close:
  
             HandleClose(socket);
  
         break;
  
         case WebSocketMessageType.Text:
             // Handle text message 
  
         break;
     }
  }
  
  if (socket.State == WebSocketState.Aborted)
  {
      // Handle aborted
  }
  else if (socket.State == WebSocketState.Closed)
  {
      HandleClose(socket);
  }
  else if (socket.State == WebSocketState.CloseReceived)
  {
  
  }
  else if (socket.State == WebSocketState.CloseSent)
  {
  }
  </code></pre>