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? });
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.
clear-ws handles reconnects automatically (if you provide not null reconnect.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With