Skip to content

Instantly share code, notes, and snippets.

@tiagosiebler
Created June 27, 2019 09:29
Show Gist options
  • Save tiagosiebler/a24a47656a267d43fc7d5f6def40b2e6 to your computer and use it in GitHub Desktop.
Save tiagosiebler/a24a47656a267d43fc7d5f6def40b2e6 to your computer and use it in GitHub Desktop.
Automatically monitors websockets for unexpected disconnects, then terminates and sockets that stopped responding. This allows the onClose event to handle reconnects.
// automatically monitors websockets for unexpected disconnects, then terminates and sockets that stopped responding.
// This allows the onClose event to handle reconnects.
const monitorWebsocket = ws => {
ws.on('error', () => {
ws.isAlive = true;
});
ws.on('close', () => {
ws.isAlive = true;
});
ws.on('open', () => {
ws.isAlive = true;
});
ws.on('pong', () => {
ws.isAlive = true;
ws.lastAlive = new Date();
});
ws.socketMonitor = setInterval(() => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
// ping will throw an exception if the ws closed earlier (e.g no network), so we'll only ping if the socket's still open
if (ws.readyState === ws.OPEN) ws.ping();
}, 10000);
};
module.exports = monitorWebsocket;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment