painor
painor

Reputation: 1237

detect websocket loss of internet client side fast

I'm using WebSockets to connect to a server that I don't have control over. This is a chat app so I am expecting when the user's internet gets cut off for any reason I would show a "reconnecting" alert and try reconnecting every 2 sec.

The issue is the .onclose event takes up to 1 min to fire up when you turn off your modem for example and there is no way for me to know if the user still has connection to the servers.

code example :

<script type="text/javascript">
    var ws = new WebSocket("wss://echo.websocket.org");
    ws.onerror = function () {
        console.log("error happened")
    }
    ws.onclose = function () {
        // websocket is closed.
        console.log("Connection is closed...");
    };
</script>

Upvotes: 0

Views: 1085

Answers (1)

nicholaswmin
nicholaswmin

Reputation: 22949

If you want to detect whether the user went offline you can simply use the offline event.

Here's an example:

window.addEventListener('offline', e => {
  console.log('offline')
})

If you insist on using the onclose/onerror handlers of WebSockets, you'd need to increase the ping interval or decrease the timeout on your WebSockets server. Judging from your OP those values seem to be set at 60 seconds.

Upvotes: 2

Related Questions