websocket对象ws nodejs中无法访问isAlive属性

时间:2019-03-02 16:58:19

标签: node.js websocket ws

我正在将ws模块用于websocket服务器和客户端,并且正在从文档页面获取示例代码。

对于我的用例,我必须使用ping / pong框架维护服务器和客户端之间的连接。

我正在服务器中使用这段代码,

const WebSocket = require('ws');

function noop() {}

function heartbeat() {
  this.isAlive = true;
}

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
});

const interval = setInterval(function ping() {
  wss.clients.forEach(function each(ws) {
    if (ws.isAlive === false) return ws.terminate();

    ws.isAlive = false;
    ws.ping(noop);
  });
}, 30000);

在客户端中,

const WebSocket = require('ws');

function heartbeat() {
  clearTimeout(this.pingTimeout);

  // Use `WebSocket#terminate()` and not `WebSocket#close()`. 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);
});

我无法访问ws对象中的isAlive属性。 也无法访问this.pingTimeout

这里有指针吗?

0 个答案:

没有答案