【发布时间】:2020-07-12 09:33:03
【问题描述】:
我目前正在开发一个 NodeJS WebSocket 服务器。为了检测断开的连接,我在这里遵循了本指南:
https://github.com/websockets/ws#how-to-detect-and-close-broken-connections
服务器端运行良好,但客户端出现问题,因为我找不到 ping 功能。
有没有人知道如何在没有库的情况下完成客户端部分?
const WebSocket = require('ws');
function heartbeat() {
clearTimeout(this.pingTimeout);
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
this.pingTimeout = setTimeout(() => {
this.terminate();
}, 30000 + 1000);
}
const client = new WebSocket('wss://echo.websocket.org/');
client.on('open', heartbeat);
client.on('ping', heartbeat);
client.on('close', function clear() {
clearTimeout(this.pingTimeout);
});
一个主要问题是我认为没有 ping 方法:
client.on('open') -> client.onopen available in JavaScript
client.on('close') -> client.onclose available in JavaScript
client.on('ping') -> How? Just how?
【问题讨论】:
-
你可以使用global
WebSocket -
这就是我正在做的,但我没有找到 ping 方法。请完整阅读我的问题。
标签: javascript node.js