In Node.js I\'m using websockets/ws for a WebSocket connection. Below is the code for the client. Let\'s say the server socket we are connecting to goes down for a minute. T
You should consider a migration to socket.io
.
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.
Reconnecting to a disconnected web socket is non-trivial, and best delegated to a library. The smallest and most actively maintained library for this purpose at the moment is reconnecting-websocket, which obsoletes joewalnes's library from the other answer. For Node.js specifically, you need to pass a constructor, such as WebSocket:
import WebSocket from 'ws';
import ReconnectingWebSocket from 'reconnecting-websocket';
const ws = new ReconnectingWebSocket('wss://some-feed.com', [], {
constructor: WebSocket,
connectionTimeout: ..., // in milliseconds
reconnectInterval: ...,
});
I've used https://github.com/joewalnes/reconnecting-websocket/blob/master/reconnecting-websocket.js with success.
You should be able to do:
ws = new ReconnectingWebSocket('ws://....');
ws.reconnectInterval = 60000; // try to reconnect after 10 seconds
Try this:
var reconnectInterval = x * 1000 * 60;
var ws;
var connect = function(){
ws = new WebSocket('ws://localhost');
ws.on('open', function() {
console.log('socket open');
});
ws.on('error', function() {
console.log('socket error');
});
ws.on('close', function() {
console.log('socket close');
setTimeout(connect, reconnectInterval);
});
};
connect();
You get to use the original implementation without having to wrap it.