Home > Enterprise >  How to detect Websocket disconnection in .Net/C#?
How to detect Websocket disconnection in .Net/C#?

Time:10-12

I have a .Net/C# server. The clients connect to the server through websockets.

I would like to detect from the server the case when the client loses internet connection.

I have the following code inside a loop that reads data coming from the client through web socket

Dim WS as Websocket 'Websocket Created somewhere else...
Dim MemoryStream As New MemoryStream()
Dim Result As WebSocketReceiveResult = Nothing
Dim Buffer As ArraySegment(Of Byte) = New ArraySegment(Of Byte)(New Byte(20000) {})

Do
    Try
        Result = Await WS.ReceiveAsync(Buffer, CancellationToken.None)
    Catch Ex As WebSocketException
        'Some exception handler
    End Try
    
    If WS.State <> WebSocketState.Open Then     '<< Break point A
        RaiseEvent Disconnected(Me)   '<<<<<< Raise websocket disconnected event
    End If

    MemoryStream.Write(Buffer.ToArray, Buffer.Offset, Result.Count)

    If Result.EndOfMessage = True Then Exit Do            
Loop

'Do something                                   '<< Break point B

To test the code, I placed break points almost everywhere then I connect a client. Once the client connected, I cut internet connection for him.

Unfortunately, no break point is hit to detect the Websocket disconnection event.

I would like to know please if there is a way to detect when a websocket object is disconnected in C# or .Net

Thanks regards,

CodePudding user response:

Reading the fine manual it would appear to me that either you'd get an exception, the handler for which you've already written, or the returned WebSocketReceiveResult (your Result object) will have a CloseStatus enum. If you're literally pulling your network cable out I wouldn't expect an instant reaction; you might have to wait for some time.

CodePudding user response:

Finally I got the explanation.

The previous code works when the internet connection is lost. However, you have to wait for 20 minutes to get an exception from the websocket. 20 minutes is very long to detect a disconnected user. So I ended up using a ping process every x seconds to detect such scenario.

  • Related