You should consider a migration to socket.io.
- It has built-in auto-reconnect functionality. And you don't have to do anything for it. It is already enabled by default.
- Surprisingly, it is compatible with older browsers, even browsers that don't support native websockets.
The code of both is very similar, but the socket.io is perhaps just a little shorter. e.g. for the server code we used to write something like this:
const WebSocketServer = require('websocket').server const ws = new WebSocketServer({ httpServer }); ws.on('request', (request) => onConnection(request)); function onConnectionRequest(request) { const connection = request.accept(null, request.origin); if (!connection) return; connection.on('message', (msg) => onMessageReceived(msg)); connection.on('close', () => onConnectionClosed()); } function onMessage(message) { if (message.type === 'utf8') { const data = message.utf8Data; const request = JSON.parse(data); // todo use request } }
Socket.io code is very similar, but just a little shorter.
const io = require('socket.io')(httpServer); io.on('connection', (socket) => onConnection(socket)); function onConnection(socket) { socket.on('message', (msg) => onMessage(msg)); socket.on('disconnect', (reason) => onDisconnect(reason)); } function onMessage(request) { // todo use request }
However, do take in mind, that you also have to rewrite the client code. e.g. For Angular I use the ngx-socket-io plugin, which simplifies the code extremely.