Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Websocket how to reconnect when server restarts

Tags:

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. The close event will fire, but what is the best way to reconnect to the socket whenever the socket on the server goes down or errors?

var ws = new WebSocket('ws://localhost');  ws.on('open', function() {     console.log('socket open'); }); ws.on('error', function() {     console.log('socket error');     // how do I reconnect to the ws after x minutes here? }); ws.on('close', function() {     console.log('socket close');     // how do I reconnect to the ws after x minutes here? }); 
like image 816
wwwuser Avatar asked Oct 30 '13 19:10

wwwuser


People also ask

How do I reconnect to WebSocket node JS?

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.

Do WebSockets reconnect automatically?

clear-ws handles reconnects automatically (if you provide not null reconnect.

When WebSocket connection is closed?

The WebSocket is closed before the connection is established error message indicates that some client code, or other mechanism, has closed the websocket connection before the connection was fully established.

Why does WebSocket disconnect?

WebSocket disconnects can occur for a variety of reasons. Usually, a disconnect means the market data isn't being consumed fast enough. There is a server-side buffer and if it fills, the connection will be delayed and then killed.


1 Answers

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.

like image 148
John Henry Avatar answered Oct 24 '22 22:10

John Henry