简体   繁体   English

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

[英]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:我有连接到外部 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)
    }
}

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?由于我已经尝试在每次连接获得onclose时重新连接到 API,那么当这已经完成相同的事情时,还有什么必要额外实现ping-pong来检测连接断开(并尝试重新连接)?

Are there circumstances under which onclose is not triggered even though the connection may have dropped?是否存在即使连接可能已断开也不会触发onclose情况?

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.如果连接被明确关闭,您几乎会立即收到onclose ,但如果连接中断,例如当您断开以太网电缆时,则需要一些时间来获得onclose ,可能不会在 TCP 检测到连接丢失之前。 This can take many minutes, depending on your settings.这可能需要几分钟,具体取决于您的设置。

It doesn't have to be Ping/Pong by the way;顺便说一下,它不一定是 Ping/Pong; a heartbeat sent by the server and received and processed in the browser is sometimes easier to implement.由服务器发送并在浏览器中接收和处理的心跳有时更容易实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM