0

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> 

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

as I said I don't own the server sadly; I'll try the offline event and report back.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.