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 |
|
6 | WebSocket 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
|
23 | npm install --save reconnecting-websocket
|
24 | ```
|
25 |
|
26 | ## Usage
|
27 |
|
28 | ### Compatible with WebSocket Browser API
|
29 |
|
30 | So this documentation should be valid:
|
31 | [MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
|
32 |
|
33 | Ping me if you find any problems. Or, even better, write a test for your case and make a pull
|
34 | request :)
|
35 |
|
36 | ### Simple usage
|
37 |
|
38 | ```javascript
|
39 | import ReconnectingWebSocket from 'reconnecting-websocket';
|
40 |
|
41 | const rws = new ReconnectingWebSocket('ws://my.site.com');
|
42 |
|
43 | rws.addEventListener('open', () => {
|
44 | rws.send('hello!');
|
45 | });
|
46 | ```
|
47 |
|
48 | ### Update URL
|
49 |
|
50 | The `url` parameter will be resolved before connecting, possible types:
|
51 |
|
52 | - `string`
|
53 | - `() => string`
|
54 | - `() => Promise<string>`
|
55 |
|
56 | ```javascript
|
57 | import ReconnectingWebSocket from 'reconnecting-websocket';
|
58 |
|
59 | const urls = ['ws://my.site.com', 'ws://your.site.com', 'ws://their.site.com'];
|
60 | let urlIndex = 0;
|
61 |
|
62 | // round robin url provider
|
63 | const urlProvider = () => urls[urlIndex++ % urls.length];
|
64 |
|
65 | const rws = new ReconnectingWebSocket(urlProvider);
|
66 | ```
|
67 |
|
68 | ```javascript
|
69 | import ReconnectingWebSocket from 'reconnecting-websocket';
|
70 |
|
71 | // async url provider
|
72 | const urlProvider = async () => {
|
73 | const token = await getSessionToken();
|
74 | return `wss://my.site.com/${token}`;
|
75 | };
|
76 |
|
77 | const rws = new ReconnectingWebSocket(urlProvider);
|
78 | ```
|
79 |
|
80 | ### Options
|
81 |
|
82 | #### Sample with custom options
|
83 |
|
84 | ```javascript
|
85 | import ReconnectingWebSocket from 'reconnecting-websocket';
|
86 | import WS from 'ws';
|
87 |
|
88 | const options = {
|
89 | WebSocket: WS, // custom WebSocket constructor
|
90 | connectionTimeout: 1000,
|
91 | maxRetries: 10,
|
92 | };
|
93 | const rws = new ReconnectingWebSocket('ws://my.site.com', [], options);
|
94 | ```
|
95 |
|
96 | #### Available options
|
97 |
|
98 | ```typescript
|
99 | type 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
|
116 | WebSocket: undefined,
|
117 | maxReconnectionDelay: 10000,
|
118 | minReconnectionDelay: 1000 + Math.random() * 4000,
|
119 | reconnectionDelayGrowFactor: 1.3,
|
120 | minUptime: 5000,
|
121 | connectionTimeout: 4000,
|
122 | maxRetries: Infinity,
|
123 | maxEnqueuedMessages: Infinity,
|
124 | startClosed: false,
|
125 | debug: false,
|
126 | ```
|
127 |
|
128 | ## API
|
129 |
|
130 | ### Methods
|
131 |
|
132 | ```typescript
|
133 | constructor(url: UrlProvider, protocols?: string | string[], options?: Options)
|
134 |
|
135 | close(code?: number, reason?: string)
|
136 | reconnect(code?: number, reason?: string)
|
137 |
|
138 | send(data: string | ArrayBuffer | Blob | ArrayBufferView)
|
139 |
|
140 | addEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
|
141 | removeEventListener(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
|
149 | binaryType: string;
|
150 | bufferedAmount: number;
|
151 | extensions: string;
|
152 | onclose: EventListener;
|
153 | onerror: EventListener;
|
154 | onmessage: EventListener;
|
155 | onopen: EventListener;
|
156 | protocol: string;
|
157 | readyState: number;
|
158 | url: string;
|
159 | retryCount: number;
|
160 | ```
|
161 |
|
162 | ### Constants
|
163 |
|
164 | ```text
|
165 | CONNECTING 0 The connection is not yet open.
|
166 | OPEN 1 The connection is open and ready to communicate.
|
167 | CLOSING 2 The connection is in the process of closing.
|
168 | CLOSED 3 The connection is closed or couldn't be opened.
|
169 | ```
|
170 |
|
171 | ## Contributing
|
172 |
|
173 | [Read here](./CONTRIBUTING.md)
|
174 |
|
175 | ## License
|
176 |
|
177 | MIT
|