Giter Site home page Giter Site logo

robust-websocket's Introduction

robust-websocket

A robust, reconnecting WebSocket client for the browser

SauceLabs Test Status

robust-websocket is a wrapper around the standard WebSocket class that implements the same interface, but can reconnect when disconnected or the user's computer comes back online.

It is error-code aware and will not reconnect on 1008 (HTTP 400 equivalent) and 1011 (HTTP 500 equivalent) by default. This behavior is fully configurable via the shouldConnect (see Usage).

  • Tests! You know it works like stated and regressions will be caught.
  • Is aware of online and offline, and won't burn up the users battery and CPU reconnected when offline, and will reconnect when it is online again.
  • Natively aware of error codes
  • Any kind of reconnect strategy is possible via functional composition

Usage

CodePen Example

Use it as you would a normal websocket:

var ws = new RobustWebSocket('ws://echo.websocket.org/')

ws.addEventListener('open', function(event) {
  ws.send('Hello!')
})

ws.addEventListener('message', function(event) {
  console.log('we got: ' + event.data)
})

But with an optional set of options you can specify as a 3rd parameter

var ws = new RobustWebSocket('ws://echo.websocket.org/', {
   // The number of milliseconds to wait before a connection is considered to have timed out. Defaults to 4 seconds.
   timeout: 4000,
  // A function that given a CloseEvent or an online event (https://developer.mozilla.org/en-US/docs/Online_and_offline_events) and the `RobustWebSocket`,
  // will return the number of milliseconds to wait to reconnect, or a non-Number to not reconnect.
  // see below for more examples; below is the default functionality.
  shouldReconnect: function(event, ws) {
    if (event.code === 1008 || event.code === 1011) return
    return [0, 3000, 10000][ws.attempts]
  },
  // A boolean indicating whether or not to open the connection automatically. Defaults to true, matching native [WebSocket] behavior.
  // You can open the websocket by calling `open()` when you are ready. You can close and re-open the RobustWebSocket instance as much as you wish.
  automaticOpen: true,
  // A boolean indicating whether to disable subscribing to the connectivity events provided by the browser.
  // By default RobustWebSocket instances use connectivity events to avoid triggering reconnection when the browser is offline. This flag is provided in the unlikely event of cases where this may not be desired.
  ignoreConnectivityEvents: false
})

The URL parameter can either be a string, or a function which returns a string. This can be useful if you need the WebSocket to reconnect to a different URL than it connected to initially:

var ws = new RobustWebSocket((ws) => {
  return ws.reconnects > 0 ? `ws://echo.websocket.org/?reconnect=${ws.reconnects}` : `ws://echo.websocket.org/`
});

shouldReconnect Examples

Reconnect with an exponetial backoff on all errors

function shouldReconnect(event, ws) {
  return Math.pow(1.5, ws.attempts) * 500
}

Reconnect immediately but only 20 times per RobustWebSocket instance

function shouldReconnect(event, ws) {
  return ws.reconnects <= 20 && 0
}

Reconnect only on some whitelisted codes, and only 3 attempts, except on online events, then connect immediately

function shouldReconnect(event, ws) {
  if (event.type === 'online') return 0
  return [1006,1011,1012].indexOf(event.code) && [1000,5000,10000][ws.attempts]
}

See documentation for CloseEvent and online event, the two types of events that shouldReconnect will receive.

Typically, websockets closed with code 1000 indicate that the socket closed normally. In these cases, robust-websocket won't call shouldReconnect (and will not attempt to reconnect), unless you set shouldReconnect.handle1000 to true.

Polyfills needed

You may need these polyfills to support older browsers

robust-websocket's People

Contributors

alexjeffburke avatar aydys avatar bilalaslamseattle avatar felipeochoa avatar jgillich avatar kiejo avatar nathanboktae avatar nguarracino avatar taiga418 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

robust-websocket's Issues

Docs error about options paramter

In the code example just after "But with an optional set of options you can specify as a 3rd parameter", the 2nd parameter is missing.

The example should read:

var ws = new RobustWebSocket('ws://echo.websocket.org/', [], {
.....

TypeScript types

Hello, I will use your lib in a project of mine, and I've implemented some typings.
Maybe you can add them if you'd like to!

declare module "robust-websocket" {
  declare class RobustWebSocket {
    constructor(streamUri: string | ((ws: WebSocket) => string), protocols: string[], options?: {
      timeout?: number;
      shouldReconnect?: (event: CloseEvent, ws: WebSocket) => number | boolean;
      automaticOpen?: boolean;
      ignoreConnectivityEvents?: boolean;
    });

    attempts: number;
    reconnects: number;
    readyState: number;
    url: string;
    protocol: string;
    extensions: string;
    bufferedAmount: number;
    binaryType: BinaryType;

    send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;

    close(code?: number, reason?: string): void;

    dispatchEvent(event: Event): boolean;


    addEventListener(type: "open", callback: (event: Event) => void): void;
    addEventListener(type: "close", callback: (event: CloseEvent) => void): void;
    addEventListener(type: "error", callback: (event: Event) => void): void;
    addEventListener(type: "message", callback: (event: MessageEvent) => void): void;

    removeEventListener(type: "open", callback: (event: Event) => void): void;
    removeEventListener(type: "close", callback: (event: CloseEvent) => void): void;
    removeEventListener(type: "error", callback: (event: Event) => void): void;
    removeEventListener(type: "message", callback: (event: MessageEvent) => void): void;
  }
}

bump version

Hey @nathanboktae thanks for the well thought of module, specially in regards to navigator online/offline.

Mind bumping version and publishing on npm (url as a function is something that I rely on)?

Many thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.