Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

reconnecting-websocket

4.0.0-rc5 • Public • Published

Reconnecting WebSocket

Build Status Coverage Status

WebSocket that will automatically reconnect if the connection is closed.

Features

  • WebSocket API compatible (same interface, Level0 and Level2 event model)
  • Fully configurable
  • Multiplatform (Web, ServiceWorkers, Node.js, React Native)
  • Dependency free (does not depend on Window, DOM or any EventEmitter library)
  • Handle connection timeouts
  • Full test coverage
  • Debug mode
  • AMD build available (see dist folder)
  • Allows changing server URL between reconnections

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;
 
// 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);

Options

Sample with custom options

import ReconnectingWebSocket from 'reconnecting-websocket';
import WS from 'ws';
 
const options = {
    WebSocket: WS, // custom WebSocket constructor
    connectionTimeout: 1000,
    maxRetries: 10,
};
const rws = new ReconnectingWebSocket('ws://my.site.com', [], options);

Available 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
};

Default values

WebSocket: undefined,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000 + Math.random() * 4000,
minUptime: 5000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 4000,
maxRetries: Infinity,
debug: false,

API

Methods

constructor(urlUrlProvider, protocols?: string | string[], options?: Options)
 
close(code?: number, reason?: string)
reconnect(code?: number, reason?: string)
 
send(datastring | ArrayBuffer | Blob | ArrayBufferView)
 
addEventListener(type'open' | 'close' | 'message' | 'error', listenerEventListener)
removeEventListener(type:  'open' | 'close' | 'message' | 'error', listenerEventListener)

Attributes

More info

binaryTypestring;
bufferedAmountnumber;
extensionsstring;
oncloseEventListener;
onerrorEventListener;
onmessageEventListener;
onopenEventListener;
protocolstring;
readyStatenumber;
urlstring;
retryCountnumber;

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

install

npm i reconnecting-websocket

Downloadsweekly downloads

12,208

version

4.0.0-rc5

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar