Search code examples
javascriptwebsocketpingpong

Why do I need ping-pong to detect websocket connection drops if I am already reconnecting onclose()?


I have code that connects to an external WebSocket API, which looks like follows:

const WebSocket = require('ws')

const ws = new WebSocket('wss://example.com/')

const connectExternalAPI() => {
    ws.onopen = () => { ws.send(JSON.stringify('example': 'message')) }

    ws.onerror = (event) => { console.error(event) }

    ws.onmessage = (event) => { console.log(event.data) }

    ws.onclose = (event) => {
        console.error(event)
        setTimeout(connectExternalAPI, 10000)
    }
}

Since I already try to reconnect to the API every time the connection gets an onclose, what is the necessity to additionally implement ping-pong to detect connection drops (and try to reconnect) when this already accomplishes the same thing?

Are there circumstances under which onclose is not triggered even though the connection may have dropped?


Solution

  • If the connection is explicitly closed, you will get an onclose almost immediately, but if the connection is broken, for instance when you disconnect the ethernet cable, it will take some time to get an onclose, probably not before TCP detects loss of connectivity. This can take many minutes, depending on your settings.

    It doesn't have to be Ping/Pong by the way; a heartbeat sent by the server and received and processed in the browser will also work and is sometimes easier to implement.