UNPKG

4.8 kBMarkdownView Raw
1# Reconnecting WebSocket
2
3[![Build Status](https://travis-ci.org/pladaria/reconnecting-websocket.svg?branch=master)](https://travis-ci.org/pladaria/reconnecting-websocket)
4[![Coverage Status](https://coveralls.io/repos/github/pladaria/reconnecting-websocket/badge.svg?branch=master&v=1)](https://coveralls.io/github/pladaria/reconnecting-websocket?branch=master)
5
6WebSocket that will automatically reconnect if the connection is closed.
7
8## Features
9
10- WebSocket API compatible (same interface, Level0 and Level2 event model)
11- Fully configurable
12- Multi-platform (Web, ServiceWorkers, Node.js, React Native)
13- Dependency free (does not depend on Window, DOM or any EventEmitter library)
14- Handle connection timeouts
15- Allows changing server URL between reconnections
16- Buffering. Will send accumulated messages on open
17- Multiple builds available (see dist folder)
18- Debug mode
19
20## Install
21
22```bash
23npm install --save reconnecting-websocket
24```
25
26## Usage
27
28### Compatible with WebSocket Browser API
29
30So this documentation should be valid:
31[MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
32
33Ping me if you find any problems. Or, even better, write a test for your case and make a pull
34request :)
35
36### Simple usage
37
38```javascript
39import ReconnectingWebSocket from 'reconnecting-websocket';
40
41const rws = new ReconnectingWebSocket('ws://my.site.com');
42
43rws.addEventListener('open', () => {
44 rws.send('hello!');
45});
46```
47
48### Update URL
49
50The `url` parameter will be resolved before connecting, possible types:
51
52- `string`
53- `() => string`
54- `() => Promise<string>`
55
56```javascript
57import ReconnectingWebSocket from 'reconnecting-websocket';
58
59const urls = ['ws://my.site.com', 'ws://your.site.com', 'ws://their.site.com'];
60let urlIndex = 0;
61
62// round robin url provider
63const urlProvider = () => urls[urlIndex++ % urls.length];
64
65const rws = new ReconnectingWebSocket(urlProvider);
66```
67
68```javascript
69import ReconnectingWebSocket from 'reconnecting-websocket';
70
71// async url provider
72const urlProvider = async () => {
73 const token = await getSessionToken();
74 return `wss://my.site.com/${token}`;
75};
76
77const rws = new ReconnectingWebSocket(urlProvider);
78```
79
80### Options
81
82#### Sample with custom options
83
84```javascript
85import ReconnectingWebSocket from 'reconnecting-websocket';
86import WS from 'ws';
87
88const options = {
89 WebSocket: WS, // custom WebSocket constructor
90 connectionTimeout: 1000,
91 maxRetries: 10,
92};
93const rws = new ReconnectingWebSocket('ws://my.site.com', [], options);
94```
95
96#### Available options
97
98```typescript
99type Options = {
100 WebSocket?: any; // WebSocket constructor, if none provided, defaults to global WebSocket
101 maxReconnectionDelay?: number; // max delay in ms between reconnections
102 minReconnectionDelay?: number; // min delay in ms between reconnections
103 reconnectionDelayGrowFactor?: number; // how fast the reconnection delay grows
104 minUptime?: number; // min time in ms to consider connection as stable
105 connectionTimeout?: number; // retry connect if not connected after this time, in ms
106 maxRetries?: number; // maximum number of retries
107 maxEnqueuedMessages?: number; // maximum number of messages to buffer until reconnection
108 startClosed?: boolean; // start websocket in CLOSED state, call `.reconnect()` to connect
109 debug?: boolean; // enables debug output
110};
111```
112
113#### Default values
114
115```javascript
116WebSocket: undefined,
117maxReconnectionDelay: 10000,
118minReconnectionDelay: 1000 + Math.random() * 4000,
119reconnectionDelayGrowFactor: 1.3,
120minUptime: 5000,
121connectionTimeout: 4000,
122maxRetries: Infinity,
123maxEnqueuedMessages: Infinity,
124startClosed: false,
125debug: false,
126```
127
128## API
129
130### Methods
131
132```typescript
133constructor(url: UrlProvider, protocols?: string | string[], options?: Options)
134
135close(code?: number, reason?: string)
136reconnect(code?: number, reason?: string)
137
138send(data: string | ArrayBuffer | Blob | ArrayBufferView)
139
140addEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
141removeEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
142```
143
144### Attributes
145
146[More info](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
147
148```typescript
149binaryType: string;
150bufferedAmount: number;
151extensions: string;
152onclose: EventListener;
153onerror: EventListener;
154onmessage: EventListener;
155onopen: EventListener;
156protocol: string;
157readyState: number;
158url: string;
159retryCount: number;
160```
161
162### Constants
163
164```text
165CONNECTING 0 The connection is not yet open.
166OPEN 1 The connection is open and ready to communicate.
167CLOSING 2 The connection is in the process of closing.
168CLOSED 3 The connection is closed or couldn't be opened.
169```
170
171## Contributing
172
173[Read here](./CONTRIBUTING.md)
174
175## License
176
177MIT