[SOLVED] The remote party closed the websocket connection without completing the handshake


I am new to WebSockets and am currently trying to implement one for a chat I’m making. However every time I run it I end up with a error saying "The remote party closed the WebSocket connection without completing the close handshake.".

Here is my current code:

public async Task Receive(ClientWebSocket socket)
        var buffer = new ArraySegment<byte>(new byte[2048]);
            WebSocketReceiveResult result;
            MemoryStream ms = new MemoryStream();
                result = await socket.ReceiveAsync(buffer, CancellationToken.None); //Errors here
                ms.Write(buffer.Array, buffer.Offset, result.Count);
            } while (!result.EndOfMessage);

            if (result.MessageType == WebSocketMessageType.Close)

            ms.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(ms, Encoding.UTF8);
            string text = await reader.ReadToEndAsync();
        } while (true);
    catch (Exception ex)
        MessageBox.Show("Error - " + ex.ToString());

It errors on result = await socket.ReceiveAsync(buffer, CancellationToken.None);

If you do keep sending messages it won’t error. However, if you leave it alone for a bit, about 30 seconds or to a minute, it eventually shows that error. The server is being ran on a VPS and that seems to be fine. Sending messages is fine too, everyone receives it. The problem is just that if you leave it alone and don’t send any messages for a bit it just throws an exception and throws that error.


I should probably post the solution. I had this code in a separate class for me to call. However, using this code in a form/window makes it work, unsure why.

Answered By – Laxion

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *