如何在JavaScript和NodeJS WebSocket之间进行Ping/Pong?

如何在JavaScript和NodeJS WebSocket之间进行Ping/Pong?,javascript,node.js,Javascript,Node.js,我目前正在开发一个NodeJS WebSocket服务器。要检测断开的连接,我遵循以下指南: 服务器端工作得很好,但是客户端出现了问题,因为我找不到ping函数 有人知道我如何在没有库的情况下完成客户机部分吗 const WebSocket = require('ws'); function heartbeat() { clearTimeout(this.pingTimeout); // Use `WebSocket#terminate()`, which immediately

我目前正在开发一个NodeJS WebSocket服务器。要检测断开的连接,我遵循以下指南:

服务器端工作得很好,但是客户端出现了问题,因为我找不到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?
没有用于发送ping帧或接收pong帧的Javascript API。您的浏览器是否支持此功能。也没有API来启用、配置或检测浏览器是否支持并正在使用乒乓帧


我想你在客户机上寻找的是
onmessage

client.onmessage = function (event) {
  console.log(event.data);
}

通过这种方式可以侦听从服务器发送的所有消息。请参见

Sad,但如果是,API不支持前面的答案中提到的

最常用的解决方法是侦听关闭事件,并尝试使用间隔重新连接到服务器

易于理解,包含从WS开始的大多数用例:

var ws = new WebSocket("ws://localhost:3000/ws");
let that = this; // cache the this
var connectInterval;
var check = () => {
    const { ws } = this.state;
    if (!ws || ws.readyState == WebSocket.CLOSED) this.connect(); //check if websocket instance is closed, if so call `connect` function.
};

// websocket onopen event listener
ws.onopen = () => {
    console.log("connected websocket main component");

    this.setState({ ws: ws });
    that.timeout = 250; // reset timer to 250 on open of websocket connection 
    clearTimeout(connectInterval); // clear Interval on on open of websocket connection
};

// websocket onclose event listener
ws.onclose = e => {
    console.log(
        `Socket is closed. Reconnect will be attempted in ${Math.min(
            10000 / 1000,
            (that.timeout + that.timeout) / 1000
        )} second.`,
        e.reason
    );

    that.timeout = that.timeout + that.timeout; //increment retry interval
    connectInterval = setTimeout(this.check, Math.min(10000, that.timeout)); //call check function after timeout
};

// websocket onerror event listener
ws.onerror = err => {
    console.error(
        "Socket encountered error: ",
        err.message,
        "Closing socket"
    );
    ws.close();
};

你可以直接使用,这就是我正在做的,但是我没有找到ping方法。请完整阅读我的问题。这回答了你的问题吗?