Skip to content

ClientWebSocket.CloseAsync hangs if internet connection is lost #51590

@ghost

Description

We have an app that connects to a websocket service with a custom "heartbeat" mechanism. On an interval, the client requests a heartbeat from the server (via websocket message), and if the server doesn't reply, the client assumes the server is gone, and reconnects.

We have essentially the following code:

if (!hasReceivedHeartbeatAck)
{
    logger.Warning("Did not receive heartbeat Ack from gateway");
    await client.Disconnect(WebSocketCloseStatus.ProtocolError, "Did not receive ACK in time", default);
    logger.Information("Connection closed, reconnecting...");
    await Reconnect();
}

(the original code is here, it calls this method then the return false propagates up a couple methods and eventually gets to this log line)

When there's a server error, this works fine - the connection is correctly closed and reconnected.
However, if the internet connection is lost (this can be reproduced by disconnecting the ethernet wire), client.Disconnect hangs until the internet connection returns, then throws the following error:

System.Net.WebSockets.WebSocketException (2): The remote party closed the WebSocket connection without completing the close handshake. ---> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer. ---> System.Net.Sockets.SocketException (104): Connection reset by peer

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions