4.4.0 • Published 5 years ago

reconnecting-websocket v4.4.0

Weekly downloads
68,590
License
MIT
Repository
github
Last release
5 years ago

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
  • 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;

// 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 to consider connection as stable
    connectionTimeout?: number; // retry connect if not connected after this time, in ms
    maxRetries?: number; // maximum number of retries
    maxEnqueuedMessages?: number; // maximum number of messages to buffer until reconnection
    startClosed?: boolean; // start websocket in CLOSED state, call `.reconnect()` to connect
    debug?: boolean; // enables debug output
};

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?: 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)

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

@estanalytical/vasconnectflokhex-ocean-django-channelsbinance-api-node-fullboydog-client@anadyme/lavva-widgetsve-playerdogehouse-jsdogehouse.js-staged@faceit/nodejs-server-plugin@mcgordonite/theia-corepublishtestformeinreactnativewebtestcomponentalias-client@radar/chain-watchers-bitcoin@fungi-realtime/core@tumakot/orion-trading-sdkexchange-connectormixineos-walletcpe-video-ad-break-uicybex-game-addongjw-livechatgjw-livechat-v2valkyriecoms-jshamro-chat-sdkjs-34@infinitebrahmanuniverse/nolb-reco@sdv-streaming/common@civfund/fund-librariesfzmtoolroam-dev-servernanocurrency.js@everything-registry/sub-chunk-2632teller-sdktc_sense_commonweb-plugin-utilswefdsacerchretnerxfewedxfwsdfwefregworkano-js-sdkws-sequencexhip-clienttele-aria2test-rxdbtheia-corevkflowvite-xiongan-jssdkvenom-player@coolita/js-sdk-communicator-websocket@dmsi/core@dogehouse/client@dogehouse/kebab@cs125/chitter@cs125/element-tracker@cs125/helpable@cs125/mace@cs124/element-tracker@cs124/mace@callybaseai/vox@bunnytube/wrapper@benbird/cf_edit@benbird/bf_design@canonical/maas-uicollab-react-componentsissueiqjwjsjnpf-webjoplin-plugin-bundlejoplin-plugin-readcube-papersipsavelkclkcnkmopoframework-uikucoin-websocket-apikucoin-websockets@kadenthomp36/homebridge-dreo@comfy-creator/graph-editorcomfy-creatorkaden-dreoqgb-cs-videosu-live-chattwitch-realtime-reconnectttlock-sdk-jstypefox-monacotingwu-meeting-sdktingwu-meeting-ui-componentstrustlines-clientlibts-alias-clienttradovate-api-nodetransactionlink-widgetv2undemagni@anypay/server@audiocloud/domain-rt-client@audiocloud/web-domain-client@ariva-mds/mds@aven-cloud/cloud-browser@aven-cloud/cloud-network@aven-cloud/cloud-server@aiocean/ai-bridge-js@axelar-network/axelar-local-dev-cosmos@agilegravity/react-sdk@britzkopf/pglet@ccyccyccy/sharedb-ace@chaingun/client
4.4.0

5 years ago

4.3.0

5 years ago

4.2.0

6 years ago

4.1.10

7 years ago

4.1.9

7 years ago

4.1.8

7 years ago

4.1.7

7 years ago

4.1.6

7 years ago

4.1.5

7 years ago

4.1.4

7 years ago

4.1.3

7 years ago

4.1.2

7 years ago

4.1.1

7 years ago

4.1.0

7 years ago

4.0.0-rc5

7 years ago

4.0.0-rc4

7 years ago

4.0.0-rc3

7 years ago

4.0.0-rc2

7 years ago

4.0.0-rc1

7 years ago

3.2.2

8 years ago

3.2.1

8 years ago

3.2.0

8 years ago

3.1.1

8 years ago

3.1.0

8 years ago

3.0.7

8 years ago

3.0.6

8 years ago

3.0.5

8 years ago

3.0.4

8 years ago

3.0.3

9 years ago

3.0.2

9 years ago

3.0.1

9 years ago

3.0.0

9 years ago

2.0.0

9 years ago

1.4.4

9 years ago

1.4.3

9 years ago

1.4.2

9 years ago

1.4.0

9 years ago

1.3.2

9 years ago

1.3.0

9 years ago

1.2.0

9 years ago

1.1.0

9 years ago

1.0.0

9 years ago

1.0.4

10 years ago

1.0.3

10 years ago

1.0.2

10 years ago