Reconnection of Client When Server Reboots in Websocket

Reconnection of Client when server reboots in WebSocket

When the server reboots, the Web Socket connection is closed, so the JavaScript onclose event is triggered. Here's an example that tries to reconnect every five seconds.

function start(websocketServerLocation){
ws = new WebSocket(websocketServerLocation);
ws.onmessage = function(evt) { alert('message received'); };
ws.onclose = function(){
// Try to reconnect in 5 seconds
setTimeout(function(){start(websocketServerLocation)}, 5000);
};
}

NodeJS Websocket how to reconnect when server restarts

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

WebSocket: How to automatically reconnect after it dies

Here is what I ended up with. It works for my purposes.

function connect() {
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function() {
// subscribe to some channels
ws.send(JSON.stringify({
//.... some message the I must send when I connect ....
}));
};

ws.onmessage = function(e) {
console.log('Message:', e.data);
};

ws.onclose = function(e) {
console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
setTimeout(function() {
connect();
}, 1000);
};

ws.onerror = function(err) {
console.error('Socket encountered error: ', err.message, 'Closing socket');
ws.close();
};
}

connect();

Python websocket-client reconnect after server restart

After release 1.4.0 of websocket-client, the problem is fixed. You don't even need to use thread in order to provide continuous tries for reconnecting to server.

class ClientSocket:
def __init__(self):
self.opened = False
self.ws = websocket.WebSocketApp("ws://localhost:8080/socket",
header={
'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9'},
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close)
self.ws.run_forever(dispatcher=rel)
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()

def on_message(self, ws, message):
print(message)

def on_error(self, ws, error):
print(error)

def on_close(self, ws, close_status_code, close_msg):
print("### closed ###")
rel.abort()
self.ws.run_forever(dispatcher=rel)
rel.signal(2, rel.abort)
rel.dispatch()

def on_open(self, ws):
print("Opened connection")
time.sleep(2)
ws.send("CONNECT\naccept-version:1.0,1.1,2.0\n\n\x00\n")

# Subscribing to all required desitnations.
sub = stomper.subscribe("/user/queue/reply", "clientuniqueId", ack="auto")
ws.send(sub)

Reconnect Interval

The question is calling for a subjective response, here is mine :)

  • Discriminating a client disconnection and a server shutdown:
    This can be achieved by sending a shutdown message over the websocket so that active clients can prepare and reconnect with a random delay. Thus, a client that encounters an onclose event without a proper shutdown broadcast would be able to reconnect asap. This means that the client application needs to be modified to account for this special shutdown event.

  • Handle the handshake load: Some web servers can handle incoming connections as an asynchronous parallel event queue, thus at most X connections will be initialized at the same time (in parallel) and others will wait in a queue until their turn comes. This allows to safeguard the server performance and the websocket handshake will thus be automatically delayed based on the true processing capabilities of the server. Of course, this means a change of web server technology and depends on your use-case.

How to reconnect to websocket after close connection

NOTE: The question is tagged socket.io so this answer is specifically regarding socket.io.

As many people have pointed out, this answer doesn't apply to vanilla websockets, which will not attempt to reconnect under any circumstances.

Websockets will not automatically try to reconnect. You'll have to recreate the socket in order to get a new connection. The only problem with that is you'll have to reattach your handlers.

But really, websockets are designed to stay open.

A better method would be to have the server close the connection. This way the websocket will fire an onclose event but will continue attempting to make the connection. When the server is listening again the connection will be automatically reestablished.

Websocket won't reconnect unless I close the browser tab and restart it

You probably need to use setInterval. Try this, you may have to tweek it a bit.

var gateway = `ws://${window.location.hostname}/ws`;
var websocket, sockTimer=null;

function initWebSocket() {
console.log('Trying to open a WebSocket connection...');
websocket = new WebSocket(gateway);
websocket.onopen = onOpen;
websocket.onerror = onError; // ç new
websocket.onclose = onClose;
websocket.onmessage = onMessage; // <-- add this line
}

function onOpen(event) {
clearInterval(sockTimer) // <= better
console.log('Connection opened');

}
function onError() { // <= New
sockTimer = setInterval(init, 1000 * 60);

};
function onClose(event) {
console.log('Connection closed');
//setTimeout(initWebSocket, 2000);
sockTimer = setInterval(initWebSocket, 1000 * 60); // <=new
}


Related Topics



Leave a reply



Submit