简体   繁体   English

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

[英]How can I do Ping/Pong between JavaScript and NodeJS WebSocket?

I'm currently developing a NodeJS WebSocket server.我目前正在开发一个 NodeJS WebSocket 服务器。 To detect broken connections I've followed this guide here:为了检测断开的连接,我在这里遵循了本指南:

https://github.com/websockets/ws#how-to-detect-and-close-broken-connections https://github.com/websockets/ws#how-to-detect-and-close-broken-connections

The server side works really good but the client makes problems because I can't find a ping function.服务器端工作得很好,但客户端出现问题,因为我找不到 ping 功能。

Does anyone has an idea how I can get the client part done without the library?有没有人知道如何在没有库的情况下完成客户端部分?

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

One main problem is that there is no ping method I think:一个主要问题是我认为没有ping方法:

client.on('open') -> client.onopen available in JavaScript
client.on('close') -> client.onclose available in JavaScript
client.on('ping') -> How? Just how?

There is no Javascript API to send ping frames or receive pong frames.没有用于发送 ping 帧或接收 pong 帧的 Javascript API。 This is either supported by your browser, or not.这要么受您的浏览器支持,要么不支持。 There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames.也没有 API 来启用、配置或检测浏览器是否支持和正在使用 ping/pong 帧。

https://stackoverflow.com/a/10586583/7377682 https://stackoverflow.com/a/10586583/7377682

Sad but true, in case of the ping frame , the API does not support it as mentioned in previous answers.可悲但真实,在ping frame 的情况下,API 不支持它,如前面的答案中所述。

The most popular workaround is to listen to the close event and try to reconnect to the server using an interval.最流行的解决方法是监听关闭事件并尝试使用间隔重新连接到服务器。

This tutorial is easy to understand and contains most use-cases to begin with WS:本教程易于理解,并包含从 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();
};

I think what you are look for on the client is onmessage :我认为您在客户端上寻找的是onmessage

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

All messages sent from the server can be listened to this way.从服务器发送的所有消息都可以通过这种方式进行侦听。 See https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications请参阅https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications

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

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