New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

reconnecting-websocket

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

reconnecting-websocket - npm Package Compare versions

Comparing version 3.2.2 to 4.0.0-rc1

CONTRIBUTING.md

50

package.json
{
"name": "reconnecting-websocket",
"version": "3.2.2",
"version": "4.0.0-rc1",
"description": "Reconnecting WebSocket",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"main": "./dist/reconnecting-websocket-cjs.js",
"module": "./dist/reconnecting-websocket.mjs",
"types": "./dist/reconnecting-websocket.d.ts",
"scripts": {
"build": "tsc",
"build-amd": "tsc -m AMD --outFile ./dist/reconnecting-websocket.amd.js",
"build": "npm run clean && rollup -c && uglifyjs --compress --mangle -o dist/reconnecting-websocket-iife.min.js dist/reconnecting-websocket-iife.js",
"test": "nyc --reporter=text-summary --reporter=lcov ava --verbose --serial test/test.js",
"clean": "rimraf dist",
"clean": "del dist && del coverage && del .nyc_output",
"report": "nyc report --reporter=html && opn coverage/index.html",
"prepublish": "npm run clean && npm run build && npm run build-amd && npm test",
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls"
"coveralls": "cat ./coverage/lcov.info | ./node_modules/.bin/coveralls",
"lint": "tslint *.ts",
"precommit": "lint-staged",
"prepublishOnly": "npm run clean && npm run lint && npm run build && npm test"
},

@@ -30,10 +32,16 @@ "keywords": [

"devDependencies": {
"ava": "^0.21.0",
"coveralls": "^2.13.1",
"html5-websocket": "^2.0.0",
"nyc": "^11.1.0",
"ava": "^0.25.0",
"coveralls": "^3.0.0",
"del-cli": "^1.1.0",
"husky": "^0.14.3",
"lint-staged": "^7.1.0",
"nyc": "^11.7.3",
"opn-cli": "^3.1.0",
"rimraf": "^2.5.4",
"typescript": "^2.4.2",
"ws": "^3.1.0"
"prettier": "^1.12.1",
"rollup": "^0.58.2",
"rollup-plugin-typescript2": "^0.14.0",
"tslint": "^5.10.0",
"typescript": "^2.8.3",
"uglify-es": "^3.3.9",
"ws": "^5.1.1"
},

@@ -54,3 +62,11 @@ "dependencies": {},

},
"homepage": "https://github.com/pladaria/reconnecting-websocket#readme"
}
"homepage": "https://github.com/pladaria/reconnecting-websocket#readme",
"lint-staged": {
"linters": {
"*.{js,md,ts}, !dist/*": [
"prettier --write",
"git add"
]
}
}
}
# Reconnecting WebSocket
[![Build Status](https://travis-ci.org/pladaria/reconnecting-websocket.svg?branch=master)](https://travis-ci.org/pladaria/reconnecting-websocket)
[![Coverage Status](https://coveralls.io/repos/github/pladaria/reconnecting-websocket/badge.svg?branch=master)](https://coveralls.io/github/pladaria/reconnecting-websocket?branch=master)
WebSocket that will automatically reconnect if the connection is closed.

@@ -10,15 +10,11 @@

- Small (~150 LOC)
- WebSocket API compatible (same interface, Level0 and Level2 event model)
- Fully configurable
- Multiplatform (Web, ServiceWorkers, Node.js, React Native)
- Dependency free (does not depends on Window, DOM or any EventEmitter library)
- Reassign event listeners when a new WebSocket instance is created
- Automatic reconnection using [RFC 6455](https://tools.ietf.org/html/rfc6455#section-7.2.3) guidelines
- Handle connection timeouts
- Full test coverage
- Debug mode
- Fast close
- AMD build available (see dist folder)
- Allows changing server URL
* WebSocket API compatible (same interface, Level0 and Level2 event model)
* Fully configurable
* Multiplatform (Web, ServiceWorkers, Node.js, React Native)
* Dependency free (does not depends 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

@@ -31,18 +27,2 @@ ## Install

## Run tests
```bash
# clone
git clone https://github.com/pladaria/reconnecting-websocket
# enter
cd reconnecting-websocket
# install deps
npm install
# run tests
npm test
# review the test coverage report
npm run report
```
## Usage

@@ -52,5 +32,7 @@

So this documentation should be valid: [MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
So this documentation should be valid:
[MDN WebSocket API](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket).
Ping me if you find any problems. Or, even better, write a test for your case and make a pull request :)
Ping me if you find any problems. Or, even better, write a test for your case and make a pull
request :)

@@ -60,3 +42,4 @@ ### Simple usage

```javascript
const ReconnectingWebSocket = require('reconnecting-websocket');
import ReconnectingWebSocket from 'reconnecting-websocket';
const rws = new ReconnectingWebSocket('ws://my.site.com');

@@ -71,6 +54,10 @@

The `url` parameter also accepts a `function` so you have a chance to update the URL before connecting:
The `url` parameter will be resolved before connecting, possible types:
* `string`
* `() => string`
* `() => Promise<string>`
```javascript
const ReconnectingWebSocket = require('reconnecting-websocket');
import ReconnectingWebSocket from 'reconnecting-websocket';

@@ -80,26 +67,22 @@ const urls = ['ws://my.site.com', 'ws://your.site.com', 'ws://their.site.com'];

// Round robin url provider
const getUrl = () => urls[urlIndex++ % urls.length];
// round robin url provider
const urlProvider = () => urls[urlIndex++ % urls.length];
const rws = new ReconnectingWebSocket(getUrl);
const rws = new ReconnectingWebSocket(urlProvider);
```
### Configure
```javascript
import ReconnectingWebSocket from 'reconnecting-websocket';
#### Default options
// async url provider
const urlProvider = async () => {
const token = await getSessionToken();
return `wss://my.site.com/${token}`;
};
Options should be self explanatory
```javascript
const defaultOptions = {
constructor: isGlobalWebSocket() ? WebSocket : null,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1500,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 4000,
maxRetries: Infinity,
debug: false,
};
const rws = new ReconnectingWebSocket(urlProvider);
```
### Options
#### Sample with custom options

@@ -109,63 +92,88 @@

const ReconnectingWebSocket = require('reconnecting-websocket');
const WS = require('ws');
const options = {connectionTimeout: 1000};
const options = {
WebSocket: WS, // custom WebSocket constructor
connectionTimeout: 1000,
maxRetries: 10,
};
const rws = new ReconnectingWebSocket('ws://my.site.com', [], options);
```
#### Manually closing
#### Available options
The `close` function has an additional options parameter
```typescript
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
```javascript
close(code = 1000, reason = '', {keepClosed: boolean, fastClose: boolean, delay: number})
WebSocket: undefined,
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000 + Math.random() * 4000,
minUptime: 5000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 4000,
maxRetries: Infinity,
debug: false,
```
- Use the `keepClosed` option to keep the WebSocket closed or automatically reconnect (default `false`).
- 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`.
- Use the `delay` option to set the initial delay for the next connection retry (ignored if `0`).
## API
#### Setting WebSocket options
### Methods
If 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:
```typescript
constructor(url: UrlProvider, protocols?: string | string[], options?: Options)
```javascript
rws.addEventListener('open', () => {
rws.binaryType = 'arraybuffer';
rws.send('i am ready to receive some data!');
});
```
close(code?: number, reason?: string)
reconnect(code?: number, reason?: string)
#### Using alternative constructor
send(data: string | ArrayBuffer | Blob | ArrayBufferView)
This 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).
addEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
removeEventListener(type: 'open' | 'close' | 'message' | 'error', listener: EventListener)
```
The example uses the [html5-websocket](https://github.com/pladaria/html5-websocket) module.
### Attributes
```javascript
const Html5WebSocket = require('html5-websocket');
const ReconnectingWebSocket = require('reconnecting-websocket');
[More info](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)
const options = {constructor: Html5WebSocket};
const rws = new ReconnectingWebSocket('ws://my.site.com', undefined, options);
```typescript
binaryType: string;
bufferedAmount: number; // read only
extensions: string;
onclose: EventListener;
onerror: EventListener;
onmessage: EventListener;
onopen: EventListener;
protocol: string;
readyState: number; // read only
url: string; // read only
```
#### Max retries
### Constants
When the max retries limit is reached, an error event with code `EHOSTDOWN` is emitted.
```text
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.
```
By default, `maxRetries` is set to `Infinity`.
## Contributing
```javascript
const ReconnectingWebSocket = require('reconnecting-websocket');
[Read here](./CONTRIBUTING.md)
const rws = new ReconnectingWebSocket('ws://my.site.com', undefined, {maxRetries: 3});
rws.onerror = (err) => {
if (err.code === 'EHOSTDOWN') {
console.log('server down');
}
};
```
## License
MIT

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc