.Net ClientWebSocket ReceiveAsync throwing The remote party closed the WebSocket

199 views Asked by At

I have a Console App that needs to send a message to a web socket and after receive messages from it.

The problem I am having is, when ClientWebSocket "ReceiveAsync" method is called, I am getting the following error message:

The remote party closed the WebSocket connection without completing the close handshake.

Here is the Exception StackTrace:

Exception thrown: 'System.Net.WebSockets.WebSocketException' in System.Private.CoreLib.dll An exception of type 'System.Net.WebSockets.WebSocketException' occurred in System.Private.CoreLib.dll but was not handled in user code The remote party closed the WebSocket connection without completing the close handshake.

And here is my code:

        var connectMsg = ConnectMsg.Replace("token", token);

        using var socket = new ClientWebSocket();

        await socket.ConnectAsync(new Uri(Uri), CancellationToken.None);

        var data = Encoding.ASCII.GetBytes(connectMsg);

        var buffer = new ArraySegment<byte>(data, 0, data.Length);

        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);         

        var reciveBuffer = new byte[32000];           

        while (socket.State == WebSocketState.Open)
        {
            var result = await socket.ReceiveAsync(new ArraySegment<byte>(reciveBuffer), CancellationToken.None);

            if (result.MessageType == WebSocketMessageType.Close)
            {
                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
            }
            else
            {
                await HandleMessage(reciveBuffer, result.Count);
            }
        }

Can anyone explain me why am I getting that Error and how I can solve it?

Bests

1

There are 1 answers

1
Bart Verkoeijen On BEST ANSWER

The underlying websocket is already closed (likely by the server), since you received the close message type, but then you initiate another client initiated close on the already closed connection, causing the exception.

if (result.MessageType == WebSocketMessageType.Close)
{
    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}

Also, you may want to buffer the messages until you receive EndOfMessage on the result.