What is reconnecting-websocket?
The 'reconnecting-websocket' npm package provides a WebSocket client that automatically reconnects if the connection is lost. It is designed to be a drop-in replacement for the standard WebSocket, adding the ability to handle disconnections and reconnections seamlessly.
What are reconnecting-websocket's main functionalities?
Automatic Reconnection
This feature allows the WebSocket to automatically reconnect if the connection is lost. The code sample demonstrates how to create a new ReconnectingWebSocket instance and handle open, close, and message events.
const ReconnectingWebSocket = require('reconnecting-websocket');
const rws = new ReconnectingWebSocket('ws://example.com');
rws.addEventListener('open', () => {
console.log('Connected');
});
rws.addEventListener('close', () => {
console.log('Disconnected');
});
rws.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
Custom Reconnection Logic
This feature allows you to customize the reconnection logic by setting options such as connection timeout, maximum retries, and reconnection delays. The code sample demonstrates how to create a ReconnectingWebSocket instance with custom options.
const ReconnectingWebSocket = require('reconnecting-websocket');
const options = {
connectionTimeout: 1000,
maxRetries: 10,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000
};
const rws = new ReconnectingWebSocket('ws://example.com', [], options);
rws.addEventListener('open', () => {
console.log('Connected');
});
rws.addEventListener('close', () => {
console.log('Disconnected');
});
rws.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
Event Handling
This feature allows you to handle various WebSocket events such as open, close, message, and error. The code sample demonstrates how to add event listeners for these events.
const ReconnectingWebSocket = require('reconnecting-websocket');
const rws = new ReconnectingWebSocket('ws://example.com');
rws.addEventListener('open', () => {
console.log('Connected');
});
rws.addEventListener('close', () => {
console.log('Disconnected');
});
rws.addEventListener('message', (event) => {
console.log('Message from server:', event.data);
});
rws.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
Other packages similar to reconnecting-websocket
ws
The 'ws' package is a simple to use, blazing fast, and thoroughly tested WebSocket client and server for Node.js. Unlike 'reconnecting-websocket', it does not provide automatic reconnection out of the box, but it offers more control and flexibility for WebSocket communication.
socket.io-client
The 'socket.io-client' package is a client library for Socket.IO, which enables real-time, bidirectional, and event-based communication. It includes automatic reconnection and other advanced features like multiplexing and broadcasting. It is more feature-rich compared to 'reconnecting-websocket' but also more complex.
websocket
The 'websocket' package provides a WebSocket client and server library for Node.js. It supports automatic reconnection through additional configuration and offers a robust set of features for WebSocket communication. It is more comprehensive compared to 'reconnecting-websocket'.
Reconnecting WebSocket
WebSocket that will automatically reconnect if the connection is closed.
Features
- Small (~150 LOC)
- WebSocket API compatible (same interface, Level0 and Level2 event model)
- Fully configurable
- Multiplatform (Web, ServiceWorkers, Node.js, React Native)
- Dependency free (does not depends on Window, DOM or any EventEmitter library)
- Reassign event listeners when a new WebSocket instance is created
- Automatic reconnection using rfc6455 guidelines
- Handle connection timeouts
- Full test coverage
- Debug mode
Install
npm install --save reconnecting-websocket
Run tests
git clone https://github.com/pladaria/reconnecting-websocket
cd reconnecting-websocket
npm install
npm test
npm run report
Usage
Compatible with WebSocket Browser API
So this documentation should be valid: MDN WebSocket API.
Ping me if you find any problems. Or, even better, write a test for your case and make a pull request :)
Simple usage
const WebSocket = require('reconnecting-websocket');
const ws = new WebSocket('ws://my.site.com');
ws.addEventListener('open', () => {
ws.send('hello!');
});
Configure
Default options
Options should be self explainatory
const defaultOptions = {
constructor: (typeof WebSocket === 'function') ? WebSocket : null,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1500,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 4000,
maxRetries: Infinity,
debug: false,
};
Sample with custom options
const WebSocket = require('reconnecting-websocket');
const options = {connectionTimeout: 1000};
const ws = new WebSocket('ws://my.site.com', null, options);
Using alternative constructor
This way you can use this module in cli/testing/node.js or use a decorated/alternative WebSocket. The only requisite is that the given constructor must be compatible with the WebSocket API.
The example uses the html5-websocket module.
const Html5WebSocket = require('html5-websocket');
const WebSocket = require('reconnecting-websocket');
const options = {constructor: Html5WebSocket};
const ws = new WebSocket('ws://my.site.com', null, options);
Max retries
When the max retries limit is reached, an error event with code EHOSTDOWN
is emitted.
By default, maxRetries
is set to Infinity
.
const WebSocket = require('reconnecting-websocket');
const ws = new WebSocket('ws://my.site.com', null, {maxRetries: 3});
ws.onerror = (err) => {
if (err.code === 'EHOSTDOWN') {
console.log('server down');
}
};
License
MIT