meme-box icon indicating copy to clipboard operation
meme-box copied to clipboard

WebSocket isAlive Checks

Open negue opened this issue 3 years ago • 0 comments

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


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

wss.on('close', function close() {
  clearInterval(interval);
});

negue avatar May 13 '21 17:05 negue