admin管理员组

文章数量:1315792

I'm currently developing a NodeJS WebSocket server. To detect broken connections I've followed this guide here:

The server side works really good but the client makes problems because I can't find a ping function.

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/');

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:

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

I'm currently developing a NodeJS WebSocket server. To detect broken connections I've followed this guide here:

https://github./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.

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/');

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:

client.on('open') -> client.onopen available in JavaScript
client.on('close') -> client.onclose available in JavaScript
client.on('ping') -> How? Just how?
Share Improve this question asked Mar 31, 2020 at 18:16 Mr. JoMr. Jo 5,2818 gold badges57 silver badges117 bronze badges 3
  • You can just use the global WebSocket – VLAZ Commented Mar 31, 2020 at 18:17
  • That’s what I‘m doing but I‘ve found no ping method. Please read my questions pletely. – Mr. Jo Commented Mar 31, 2020 at 18:23
  • Does this answer your question? Sending websocket ping/pong frame from browser – TheGr8_Nik Commented Mar 31, 2020 at 18:27
Add a ment  | 

3 Answers 3

Reset to default 4

There is no Javascript API to send ping frames or receive pong frames. 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.

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

Sad but true, in case of the ping frame, the API does not support it as mentioned in previous answers.

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:

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 ponent");

    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:

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

All messages sent from the server can be listened to this way. See https://developer.mozilla/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications

本文标签: nodejsHow can I do PingPong between JavaScript and NodeJS WebSocketStack Overflow