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

universal-reconnecting-websocket

v2.0.0

Published

A universal, reconnecting, event based WebSocket abstraction with configurable backoff

Downloads

16

Readme

universal-reconnecting-websocket

npm version build status coverage downloads js-standard-style

A universal, reconnecting, event based WebSocket abstraction with configurable backoff.

Installation

$ npm install universal-reconnecting-websocket

Usage

const URWS = require("universal-reconnecting-websocket")

const ws = new URWS('wss://example.com')

ws.on('state', console.log) // handler connection state
ws.on('error', console.error) // handle / display errors
ws.on('info', console.debug) // handle non-error status events

ws.on('connect', () => { // Handle the connect event maybe
  ws.send({ // default serializer is JSON
    type: 'handshake',
    foo: 'bar'
  })
})

ws.on('reconnect', () => { // Reconnection handlers can be the same function or a separate function
  ws.send({
    type: 'handshakeWithResume',
    foo: 'bar'
  })
})

ws.on('disconnect', () => {
  console.log('ws fully disconnected')
})

ws.on('message', (ev) => {
  // ev is the raw message event from the websocket
  // ev.data is the raw data payload
  console.log('Received message: ')
  console.log(ev.body.foo.bar) // default de-serializer is JSON
  // deserialized object is found on ev.body
  console.log(ev.data) // raw message data
})

ws.start()

setTimeout(() => {
  ws.stop() // turn off the websocket after a while
}, 10e10)

API

URWS = require("universal-reconnecting-websocket")

Import the URWS class.

ws = new URWS(url, [opts])

Create a URWS instance that will connect to a ws or wss url. (e.g. wss://example.com) and an opts object.

Optional opts include:

{
  serializer: JSON.stringify, // Default message serializer
  deserializer: JSON.parse, // Default deserializer
  strategy: 'fibonacci', // default backoff strategy
  protocols: null, // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket
  binaryType: null, // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/binaryType
  strategyOpts: { // backoff options argument
    randomisationFactor: 0.2, // No deep merging is performed.
    initialDelay: 1000, // If you need to change these, you have to repass the whole object
    maxDelay: 20000 // https://github.com/MathieuTurcotte/node-backoff
  },
  transport, // native WebSockets, https://github.com/websockets/ws, or pass in your own
  nodeOpts, // opts for ws in node https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketaddress-protocols-options
  failAfter: null, // fail after n failed connection attempts
  name: 'urws-' + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) // name timing events
}

ws.state

A getter that returns the current state of the URWS instance. One of:

  • disconnected: is disconnected and idle.
  • waiting: waiting to reconnect within the backoff timing
  • error: websocket is disconnected and idle due to an unrecoverable error
  • reconnecting: websocket is attempting to reconnect after being disconnected and waiting.
  • connecting: websocket is attempting to connect for the first time.
  • connected: websocket is connected and open.

ws.binaryType

A getter/setter that returns the configured binaryType option. If unset, it defaults to whatever the default binaryType the WebSocket transport defaults to. If that is unknown, it will return undefined.

When using native WebSockets it will be or can be set to one of:

  • 'blob',
  • 'arraybuffer'

ws.start()

Start the websocket connection until ws.stop() is called, or opts.failAfter consecutive reconnection attempts fail.

ws.stop()

Disconnect any active websocket connections, cancel any outstanding reconnection attempts and remove all underlying event listeners from existing WebSockets.

ws.send(msg)

Send a msg over a WebSocket. opts.serializer is automatically applied to msg and the result is sent to the WebSocket server. If you try to send when not in a connected state, the msg is discarded and an error event is fired. Any errors while running opts.serializer cause the msg to be discarded and an error event is fired. In both cases, the error will contain the original message as err.msg. Setting opts.serializer to null or undefined disables any automatic attempt to serialize your message.

Events

The ws instance emits the following node style events. They should all be handled.

ws.on('state', (stateString) => {})

Listen to the state event to get state string updates as they are generated. If stateString === error, the URWS encountered an unrecoverable error and is not attempting to reconnect any further.

ws.on('error', (err) => {})

Listen to error events to receive various errors that are encountered. You may wish to display or log these somewhere to provide better visibility of connection state, but some of these may easily be ignored. If the error originated from an underlying WebSocket event, the event will be available on err.ev.

ws.on('info', (ev) => {})

Listen to the info event to get information about clean connection close events. Sometimes websocket servers limit connection time, or need to restart etc. The ev will be an instance of CloseEvent.

ws.on('connect', (ev) => {})

Fired on the first successful connection after calling ws.start(). See more on the onopen event.

ws.on('reconnect', (ev) => {})

Fired on the second and any subsequent successful connection attempts. Useful for handling resume logic or other mid-session handshake actions. See more on the onopen event.

ws.on('disconnect' () => {})

Fired after all event listeners have been removed and the websocket has been successfully closed.

ws.on('message', (data) => {})

Fired whenever the client receives a message from the WebSocket server. Data will be the contents of the received message.

If the opts.deserializer option is set, the ev.data field will be deserialized into ev.body. Any errors during that process will prevent the message event from firing, and an error event will be fired instead, with the original ev attached as `err.

With native websockets, this event receives an ev will be of type MessageEvent, but only the data of the message is passed to the event listener. See more on the onmessage event. If needed we can expose this, but for now its abstracted away in order to pairty ws in the browser.

Setting the opts.deserializer option to null or undefined prevents any automatic attempts at deserializing and the ev.body property will be undefined.

License

MIT