Gabriel kotev
Gabriel kotev

Reputation: 369

Handling closed websocket connection in asp.net core server

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.

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!

while (socket.State == WebSocketState.Open)
{
   var cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(3000));
   buffer = new ArraySegment<byte>(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)
{
}

Upvotes: 4

Views: 7235

Answers (1)

In case the client closes the connection unexpectedly, ReceiveAsync will throw a WebSocketException.

try
{
    var received = await webSocketConnection.ReceiveAsync(...);
}
catch(WebSocketException webSocketException)
{
    if(webSocketException.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
    {
        //custom logic
    }
}

Upvotes: 7

Related Questions