npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@october/reconnecting-websocket

v2.0.0

Published

Reconnecting WebSocket

Downloads

12

Readme

Reconnecting WebSocket

Build Status Coverage Status

WebSocket that will automatically reconnect if the connection is closed.

Features

  • 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 guidelines
  • Handle connection timeouts
  • Full test coverage
  • Debug mode
  • Fast close
  • AMD build available (see dist folder)
  • Allows changing server URL

Install

npm install --save reconnecting-websocket

Run tests

# 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

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

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

rws.addEventListener('open', () => {
    rws.send('hello!');
});

Update URL

The url parameter also accepts a function so you have a chance to update the URL before connecting:

const ReconnectingWebSocket = require('reconnecting-websocket');

const urls = ['ws://my.site.com', 'ws://your.site.com', 'ws://their.site.com'];
let urlIndex = 0;

// Round robin url provider
const getUrl = () => urls[urlIndex++ % urls.length];

const rws = new ReconnectingWebSocket(getUrl);

Configure

Default options

Options should be self explanatory

const defaultOptions = {
    constructor: isGlobalWebSocket() ? WebSocket : null,
    maxReconnectionDelay: 10000,
    minReconnectionDelay: 1500,
    reconnectionDelayGrowFactor: 1.3,
    connectionTimeout: 4000,
    maxRetries: Infinity,
    debug: false,
};

Sample with custom options

const ReconnectingWebSocket = require('reconnecting-websocket');

const options = {connectionTimeout: 1000};
const rws = new ReconnectingWebSocket('ws://my.site.com', [], options);

Manually closing

The close function has an additional options parameter

close(code = 1000, reason = '', {keepClosed: boolean, fastClose: boolean, delay: number})
  • 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).

Setting WebSocket options

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:

rws.addEventListener('open', () => {
    rws.binaryType = 'arraybuffer';
    rws.send('i am ready to receive some data!');
});

Using alternative constructor

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.

The example uses the html5-websocket module.

const Html5WebSocket = require('html5-websocket');
const ReconnectingWebSocket = require('reconnecting-websocket');

const options = {constructor: Html5WebSocket};
const rws = new ReconnectingWebSocket('ws://my.site.com', undefined, options);

Max retries

When the max retries limit is reached, an error event with code EHOSTDOWN is emitted.

By default, maxRetries is set to Infinity.

const ReconnectingWebSocket = require('reconnecting-websocket');

const rws = new ReconnectingWebSocket('ws://my.site.com', undefined, {maxRetries: 3});
rws.onerror = (err) => {
    if (err.code === 'EHOSTDOWN') {
        console.log('server down');
    }
};

License

MIT