Reconnection of Client when server reboots in WebSocket
Solution 1:
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);
};
}
Solution 2:
The solution given by Andrew isn't perfectly working because, in case of lost connection, the server might send several close events.
In that case, you'll set several setTimout's. The solution given by Andrew may only work if the server is ready before five seconds.
Then, based on Andrew solution, reworked, I've made use of setInterval attaching the ID to the window object (that way it is available "everywhere"):
var timerID=0;
var socket;
/* Initiate what has to be done */
socket.onopen=function(event){
/* As what was before */
if(window.timerID){ /* a setInterval has been fired */
window.clearInterval(window.timerID);
window.timerID=0;
}
/* ... */
}
socket.onclose=function(event){
/* ... */
if(!window.timerID){ /* Avoid firing a new setInterval, after one has been done */
window.timerID=setInterval(function(){start(websocketServerLocation)}, 5000);
}
/* That way, setInterval will be fired only once after losing connection */
/* ... */
}
Solution 3:
ReconnectingWebSocket
There is a small JavaScript library that decorates the WebSocket API to provide a WebSocket connection that will automatically reconnect if the connection is dropped.
Minified library with gzip compression is less than 600 bytes.
The repository is available here:
https://github.com/joewalnes/reconnecting-websocket
There is also a TypeScript Library. Just include it and replace new WebSocket
with new ReconnectingWebSocket
.
The repository is available here:
https://github.com/pladaria/reconnecting-websocket
Server flood
If a high number of clients are connected to the server when it reboots. It may be worthwhile to manage the reconnect timings of the clients by using an Exponential Backoff algorithm.
The algorithm works like this:
- For k attempts, generate a random interval of time between 0 and 2^k - 1,
- If you are able to reconnect, reset k to 1,
- If reconnection fails, k increases by 1 and the process restarts at step 1,
- To truncate the max interval, when a certain number of attempts k has been reached, k stops increasing after each attempt.
Référence:
http://blog.johnryding.com/post/78544969349/how-to-reconnect-web-sockets-in-a-realtime-web-app
ReconnectingWebSocket does not handle reconnections by using this algorithm.
Solution 4:
I have been using this patten for a while for pure vanilla JavaScript, and it supports a few more cases than the other answers.
document.addEventListener("DOMContentLoaded", function() {
'use strict';
var ws = null;
function start(){
ws = new WebSocket("ws://localhost/");
ws.onopen = function(){
console.log('connected!');
};
ws.onmessage = function(e){
console.log(e.data);
};
ws.onclose = function(){
console.log('closed!');
//reconnect now
check();
};
}
function check(){
if(!ws || ws.readyState == 3) start();
}
start();
setInterval(check, 5000);
});
This will retry as soon as the server closes the connection, and it will check the connection to make sure it's up every 5 seconds also.
So if the server is not up when this runs or at the time of the onclose event the connection will still come back once it's back online.
NOTE: Using this script will not allow you to ever stop trying to open a connection... but I think that's what you want?