我正在开发一个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?
WebSocket
。 - VLAZ