-
Notifications
You must be signed in to change notification settings - Fork 13
Client side Auto Reconnect
Blake Miner edited this page Aug 28, 2017
·
1 revision
Auto-reconnect is not a feature of ws-wrapper
.
It can be implemented manually or using another lib. Here's an example of random exponential back-off...
const WebSocketWrapper = require("ws-wrapper");
// Exponential back-off configuration for auto-reconnect
const RECONNECT_VALUE_MIN = 1000 // 1 second
, RECONNECT_VALUE_MAX = 1000 * 60 // 1 minute
, RECONNECT_VALUE_FACTOR = 1.4;
let reconnectValue = RECONNECT_VALUE_MIN;
// Create new WebSocketWrapper
let socket = new WebSocketWrapper(null, {
"requestTimeout": 8 * 1000 // 8 seconds; kept short to catch bugs
});
socket.autoReconnect = true;
socket.on("error", (err) => {
socket.disconnect();
}).on("disconnect", function(event, wasOpen) {
// Use exponential back-off to reconnect if `autoReconnect` is set
if(wasOpen) {
reconnectValue = RECONNECT_VALUE_MIN;
} else {
reconnectValue = Math.min(reconnectValue * RECONNECT_VALUE_FACTOR,
RECONNECT_VALUE_MAX);
}
if(this.autoReconnect) {
setTimeout(() => {
socket.bind(new WebSocket("ws://" + location.host) );
}, Math.random() * reconnectValue);
}
});
// Wait for DOM to load and then connect
document.addEventListener("DOMContentLoaded", () => {
socket.bind(new WebSocket("ws://" + location.host) );
});