Created
June 27, 2019 09:29
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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