UNPKG

4.46 kBMarkdownView Raw
1# Reconnecting WebSocket
2[![Build Status](https://travis-ci.org/pladaria/reconnecting-websocket.svg?branch=master)](https://travis-ci.org/pladaria/reconnecting-websocket)
3[![Coverage Status](https://coveralls.io/repos/github/pladaria/reconnecting-websocket/badge.svg?branch=master)](https://coveralls.io/github/pladaria/reconnecting-websocket?branch=master)
4
5
6WebSocket that will automatically reconnect if the connection is closed.
7
8## Features
9
10- Small (~150 LOC)
11- WebSocket API compatible (same interface, Level0 and Level2 event model)
12- Fully configurable
13- Multiplatform (Web, ServiceWorkers, Node.js, React Native)
14- Dependency free (does not depends on Window, DOM or any EventEmitter library)
15- Reassign event listeners when a new WebSocket instance is created
16- Automatic reconnection using [rfc6455](https://tools.ietf.org/html/rfc6455#section-7.2.3) guidelines
17- Handle connection timeouts
18- Full test coverage
19- Debug mode
20- Fast close (new in version 3)
21- AMD build available (see dist folder)
22
23## Install
24
25```bash
26npm install --save reconnecting-websocket
27```
28
29## Run tests
30
31```bash
32# clone
33git clone https://github.com/pladaria/reconnecting-websocket
34# enter
35cd reconnecting-websocket
36# install deps
37npm install
38# run tests
39npm test
40
41# review the test coverage report
42npm run report
43```
44
45## Usage
46
47### Compatible with WebSocket Browser API
48
49So this documentation should be valid: [MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
50
51Ping me if you find any problems. Or, even better, write a test for your case and make a pull request :)
52
53### Simple usage
54
55```javascript
56const WebSocket = require('reconnecting-websocket');
57const ws = new WebSocket('ws://my.site.com');
58
59ws.addEventListener('open', () => {
60 ws.send('hello!');
61});
62```
63
64### Configure
65
66#### Default options
67
68Options should be self explanatory
69
70```javascript
71const defaultOptions = {
72 constructor: isGlobalWebSocket() ? WebSocket : null,
73 maxReconnectionDelay: 10000,
74 minReconnectionDelay: 1500,
75 reconnectionDelayGrowFactor: 1.3,
76 connectionTimeout: 4000,
77 maxRetries: Infinity,
78 debug: false,
79};
80```
81
82#### Sample with custom options
83
84```javascript
85const WebSocket = require('reconnecting-websocket');
86
87const options = {connectionTimeout: 1000};
88const ws = new WebSocket('ws://my.site.com', [], options);
89```
90
91#### Manually closing
92
93The `close` function has an additional options parameter
94
95```javascript
96close(code = 1000, reason = '', {keepClosed: boolean, fastClose: boolean, delay: number})
97```
98
99- Use the `keepClosed` option to keep the WebSocket closed or automatically reconnect (default `false`).
100- If `fastClose` option is `true`, all close listeners are executed as soon as the close() method is called, otherwise it waits until the websocket closing protocol finishes, this can be a long time if there's no connection (default `true`). Keep in mind that with this option, it may happen that the close event is fired with a ready state of `CLOSING`.
101- Use the `delay` option to set the initial delay for the next connection retry (ignored if `0`).
102
103#### Setting WebSocket options
104
105If you set any attributes of WebSocket itself, such as `binaryType`, make sure to set them again after each reconnection, i.e. on the `open` event:
106
107```javascript
108ws.addEventListener('open', () => {
109 ws.binaryType = 'arraybuffer';
110 ws.send('i am ready to receive some data!');
111});
112```
113
114#### Using alternative constructor
115
116This way you can use this module in cli/testing/node.js or use a decorated/alternative WebSocket. The only requisite is that the given constructor must be compatible with the [WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
117
118The example uses the [html5-websocket](https://github.com/pladaria/html5-websocket) module.
119
120```javascript
121const Html5WebSocket = require('html5-websocket');
122const WebSocket = require('reconnecting-websocket');
123
124const options = {constructor: Html5WebSocket};
125const ws = new WebSocket('ws://my.site.com', undefined, options);
126```
127
128#### Max retries
129
130When the max retries limit is reached, an error event with code `EHOSTDOWN` is emitted.
131
132By default, `maxRetries` is set to `Infinity`.
133
134```javascript
135const WebSocket = require('reconnecting-websocket');
136
137const ws = new WebSocket('ws://my.site.com', undefined, {maxRetries: 3});
138ws.onerror = (err) => {
139 if (err.code === 'EHOSTDOWN') {
140 console.log('server down');
141 }
142};
143```
144
145## License
146
147MIT