Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
reconnecting-websocket
Advanced tools
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.
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);
});
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.
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.
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'.
WebSocket that will automatically reconnect if the connection is closed.
npm install --save reconnecting-websocket
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 :)
import ReconnectingWebSocket from 'reconnecting-websocket';
const rws = new ReconnectingWebSocket('ws://my.site.com');
rws.addEventListener('open', () => {
rws.send('hello!');
});
The url
parameter will be resolved before connecting, possible types:
string
() => string
() => Promise<string>
import ReconnectingWebSocket from 'reconnecting-websocket';
const urls = ['ws://my.site.com', 'ws://your.site.com', 'ws://their.site.com'];
let urlIndex = 0;
// round robin url provider
const urlProvider = () => urls[urlIndex++ % urls.length];
const rws = new ReconnectingWebSocket(urlProvider);
import ReconnectingWebSocket from 'reconnecting-websocket';
// async url provider
const urlProvider = async () => {
const token = await getSessionToken();
return `wss://my.site.com/${token}`;
};
const rws = new ReconnectingWebSocket(urlProvider);
const ReconnectingWebSocket = require('reconnecting-websocket');
const WS = require('ws');
const options = {
WebSocket: WS, // custom WebSocket constructor
connectionTimeout: 1000,
maxRetries: 10,
};
const rws = new ReconnectingWebSocket('ws://my.site.com', [], options);
type Options = {
WebSocket?: any; // WebSocket constructor, if none provided, defaults to global WebSocket
maxReconnectionDelay?: number; // max delay in ms between reconnections
minReconnectionDelay?: number; // min delay in ms between reconnections
reconnectionDelayGrowFactor?: number; // how fast the reconnection delay grows
minUptime?: number; // min time in ms do consider connection as stable
connectionTimeout?: number; // retry connect if not connected after this time, in ms
maxRetries?: number; // maximum number of retries
debug?: boolean; // enables debug output
};
WebSocket: undefined,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000 + Math.random() * 4000,
minUptime: 5000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 4000,
maxRetries: Infinity,
debug: false,
constructor(url: UrlProvider, protocols?: string | string[], options?: Options)
close(code?: number, reason?: string)
reconnect(code?: number, reason?: string)
send(data: string | ArrayBuffer | Blob | ArrayBufferView)
addEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
removeEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
binaryType: string;
bufferedAmount: number; // read only
extensions: string;
onclose: EventListener;
onerror: EventListener;
onmessage: EventListener;
onopen: EventListener;
protocol: string;
readyState: number; // read only
url: string; // read only
CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or couldn't be opened.
MIT
FAQs
Reconnecting WebSocket
The npm package reconnecting-websocket receives a total of 207,280 weekly downloads. As such, reconnecting-websocket popularity was classified as popular.
We found that reconnecting-websocket demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.