如果我已经重新连接 onclose(),为什么我需要 ping-pong 来检测 websocket 连接断开?

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

我有连接到外部 WebSocket API 的代码,如下所示:

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)
    }
}

既然我已经尝试在每次连接获得 onclose 时重新连接到 API,那么有什么必要额外实施 ping-pong 来检测连接断开(并尝试重新连接)当这已经完成了同样的事情?

是否存在即使连接断开也未触发 onclose 的情况?

如果连接明确关闭,您几乎会立即收到 onclose,但如果连接断开,例如当您断开以太网电缆时,需要一些时间才能收到 onclose,可能不会在 TCP 检测到连接丢失之前。这可能需要很多分钟,具体取决于您的设置。

顺便说一下,它不一定是 Ping/Pong;由服务器发送并在浏览器中接收和处理的心跳有时更容易实现。