Wrapper over the WebSocket class to manage disconnections transparently.
- With npm:
$ npm install websocketwrapper
var WebSocketWrapper = require('websocketwrapper');
var ws = new WebSocketWrapper(url, protocol);
ws.reconnectionDelay = 5000;
ws.onopen = function() {
console.log('connected');
// Send some kind of registration message.
ws.send('REGISTER');
};
ws.onreconnect = function() {
console.log('reconnected');
// Send some kind of registration message.
ws.send('REGISTER');
};
ws.onmessage = function(e) {
// do something
};
An instance of WebSocketWrapper
holds an instance of a native WebSocket. The exposed API is the same as the native one. Just some differences/additions are described below.
url
andprotocols
mean the same as in the native API.
open
event is fired for the first WebSocket connection. If the connection is closed by the server or due to a netwotk error then close
is fired and, after a delay, a new connection is attempted. If it connects to the server, reconnect
event is fired.
Reconnection delay (in milliseconds). Default value is 5000 ms. If it's set to 0 no reconnection attempt will be performed.
ws.reconnectionDelay = 2000;
The library includes the Node debug module and produces logs with prefix WebSocketWrapper
.
Iñaki Baz Castillo.
ISC.