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
; const rws = 'ws://my.site.com'; rws;
Update URL
The url
parameter will be resolved before connecting, possible types:
string
() => string
() => Promise<string>
; const urls = 'ws://my.site.com' 'ws://your.site.com' 'ws://their.site.com';let urlIndex = 0; // round robin url providerconst urlProvider = urlsurlIndex++ % urlslength; const rws = urlProvider;
; // async url providerconst urlProvider = async { const token = await ; return `wss://my.site.com/`;}; const rws = urlProvider;
Options
Sample with custom options
;; const options = WebSocket: WS // custom WebSocket constructor connectionTimeout: 1000 maxRetries: 10;const rws = 'ws://my.site.com' options;
Available options
;
Default values
WebSocket: undefinedmaxReconnectionDelay: 10000minReconnectionDelay: 1000 + Math * 4000reconnectionDelayGrowFactor: 13minUptime: 5000connectionTimeout: 4000maxRetries: InfinitymaxEnqueuedMessages: InfinitystartClosed: falsedebug: false
API
Methods
constructorurl: UrlProvider, protocols?: string | string, options?: Options closecode?: number, reason?: stringreconnectcode?: number, reason?: string senddata: string | ArrayBuffer | Blob | ArrayBufferView addEventListenertype: 'open' | 'close' | 'message' | 'error', listener: EventListenerremoveEventListenertype: 'open' | 'close' | 'message' | 'error', listener: EventListener
Attributes
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
License
MIT