Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake

I have a Xamarin app that communicates using WebSocket. On the client side, I am referencing the ClientWebSocket.

code:

using (var client = new ClientWebSocket() { Options = { KeepAliveInterval = new TimeSpan(0,0,3,0) }})
{
    try
    {
        await client.ConnectAsync(requestUri, cancellationToken);
        do
        {
            WebSocketReceiveResult result = null;
            var buffer = new byte[ReceiveChunkSize];
            var message = new ArraySegment<byte>(buffer);
            do
            {
                result = await client.ReceiveAsync(message, cancellationToken);
                var receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
                data.Append(receivedMessage);
                if (result.MessageType != WebSocketMessageType.Text)
                    break;

            } while (!result.EndOfMessage);

            TranslateData(data);
        } while (client.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested);

The application keeps throwing intermittently:

 System.Net.WebSockets.WebSocketException (0x80004005): The remote
 party closed the WebSocket connection without completing the close
 handshake.

The server has a test website where it seems to function as expected. It seems the problem is on the client. The value in the client.State is Open.

like image 344
Arshad Badar Khan Avatar asked Nov 18 '25 11:11

Arshad Badar Khan


1 Answers

If anybody still findes the question like me...

I had the same problem and I added this check

result = await client.ReceiveAsync(message, cancellationToken);

if (result.Count == 0) {
    break;
}

Getting zero bytes somehow also means that the server ended the connection or something went wrong...

And I added a timer around the WebSocket to do a ping -> pong type check of the connection. Of course this is only possible if you also control the server side code. On the server side this helps you, to detect dead connections.

Links that helped me were:

https://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html

https://social.msdn.microsoft.com/Forums/vstudio/en-US/77bda5ed-0d52-4305-9a20-438e69dc2cb0/c-advanced-socket-server-100-cpu-usage-after-some-time?forum=csharpgeneral

And - like aleha_84 wrote. An exception in your loop should also trigger a reconnect.

like image 132
Markus Avatar answered Nov 20 '25 02:11

Markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!