(TODO: more)
Reconnecting WebSocket
WebSocket that will automatically reconnect if the connection is closed.
Features
- WebSocket API compatible (same interface, Level0 and Level2 event model)
- Fully configurable
- Multi-platform (Web, ServiceWorkers, Node.js, React Native)
- Dependency free (does not depend on Window, DOM or any EventEmitter library)
- Handle connection timeouts
- Allows changing server URL between reconnections
- Buffering. Will send accumulated messages on open
- Multiple builds available (see dist folder)
- Debug mode
Install
npm install --save reconnecting-websocket
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
import ReconnectingWebSocket from "reconnecting-websocket";
const rws = new ReconnectingWebSocket("ws://my.site.com");
rws.addEventListener("open", () => {
rws.send("hello!");
});
Update URL
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;
const urlProvider = () => urls[urlIndex++ % urls.length];
const rws = new ReconnectingWebSocket(urlProvider);
import ReconnectingWebSocket from "reconnecting-websocket";
const urlProvider = async () => {
const token = await getSessionToken();
return `wss://my.site.com/${token}`;
};
const rws = new ReconnectingWebSocket(urlProvider);
Update Protocols
The protocols
parameter will be resolved before connecting, possible types:
null
string
string[]
() => string | string[] | null
() => Promise<string | string[] | null>
import ReconnectingWebSocket from 'reconnecting-websocket`;
const rws = new ReconnectingWebSocket('ws:
import ReconnectingWebSocket from 'reconnecting-websocket`;
const protocols = ['p1', 'p2', ['p3.1', 'p3.2']];
let protocolsIndex = 0;
// round robin protocols provider
const protocolsProvider = () => protocols[protocolsIndex++ % protocols.length];
const rws = new ReconnectingWebSocket('ws:
Options
Sample with custom options
import ReconnectingWebSocket from "reconnecting-websocket";
import WS from "ws";
const options = {
WebSocket: WS,
connectionTimeout: 1000,
maxRetries: 10,
};
const rws = new ReconnectingWebSocket("ws://my.site.com", [], options);
Available options
type Options = {
WebSocket?: any;
maxReconnectionDelay?: number;
minReconnectionDelay?: number;
reconnectionDelayGrowFactor?: number;
minUptime?: number;
connectionTimeout?: number;
maxRetries?: number;
maxEnqueuedMessages?: number;
startClosed?: boolean;
debug?: boolean;
};
Default values
WebSocket: undefined,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000 + Math.random() * 4000,
reconnectionDelayGrowFactor: 1.3,
minUptime: 5000,
connectionTimeout: 4000,
maxRetries: Infinity,
maxEnqueuedMessages: Infinity,
startClosed: false,
debug: false,
API
Methods
constructor(url: UrlProvider, protocols?: ProtocolsProvider, 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)
Attributes
More info
binaryType: string;
bufferedAmount: number;
extensions: string;
onclose: EventListener;
onerror: EventListener;
onmessage: EventListener;
onopen: EventListener;
protocol: string;
readyState: number;
url: string;
retryCount: number;
Constants
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.
Contributing
Read here
License
MIT