graceful-ws
TypeScript icon, indicating that this package has built-in type declarations

1.3.4 • Public • Published

Logo

Graceful WebSocket wrapper

gzip size brotli size Build Status Download count No dependencies JSDelivr download count Current version Support me


graceful-ws is a WebSocket - wrapper which tries to keep a connection alive by sending a ping request every n milliseconds. It will automatically re-bind all event-listeners after a re-establishment of the connection hence making the usage of it seamless.

Getting Started

Install via npm:

$ npm install graceful-ws

Install via yarn:

$ yarn add graceful-ws

Include directly via jsdelivr:

<script src="https://cdn.jsdelivr.net/npm/graceful-ws/lib/graceful-ws.min.js"></script>

Using JavaScript Modules:

import {...} from 'https://cdn.jsdelivr.net/npm/graceful-ws/lib/graceful-ws.min.mjs'

Usage

const ws = new GracefulWebSocket('ws://localhost:8080');

// Connection-state related events
ws.addEventListener('connected', () => console.log('[WS] Connected'));
ws.addEventListener('disconnected', () => console.log('[WS] Disconnected'));
ws.addEventListener('killed', () => console.log('[WS] Killed'));

// Message event
ws.addEventListener('message', e => {
    console.log('[WS] Message received: ', e.data);
});

All options

const ws = new GracefulWebSocket({

    // Timing settings
    pingTimeout: 2500,   // After how many ms a connection should be declared as disconnected
    pingInterval: 5000,  // Ping interval
    retryInterval: 1000, // Reconnect interval in case of losing the connection

    // Ping message and expected answer
    com: {
        message: '__PING__', // Message which will be send to the server as question "hey, are you still there?"
        answer: '__PONG__'   // Expected response to the message
    },

    /**
     * Websocket parameters. ws.url is required to initialize GracefulWebsocket, otherwise an error will be thrown.
     * See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket#Parameters
     */
    ws: {
        url: 'ws://...', // WebSocket url
        protocol: 'protocols...' // Optional protocols as string or array of strings
    }
});

Functions

  • ws.addEventlistener(type, callback, options?) - Adds a new eventlistener, see events section.
  • ws.removeEventListener(type, callback, options?) - Removes an eventlistener, see events section.
  • ws.send(data) - Same as WebSocket.prototype.send, will throw an Error if there's currently no open connection.
  • ws.close(code?) - Same as WebSocket.prototype.close emits a close event, will throw an Error if the connection is already closed. (It won't restart after this function got called!)

All websocket properties (except eventlistener-related properties like onclose, onmessage etc...) are implemented by graceful-ws. add/removeEventListener is handled by graceful-ws and cannot / shouldn't be accessed directly. If there's no active connection null will be returned.

Properties

  • ws.connected: boolean - true if a connection exists. (getter)
  • ws.pingInterval: number - Ping-interval option. (getter + setter)
  • ws.pingTimeout: number - Ping-timeout option. (getter + setter)
  • ws.retryInterval: number - Retry-interval option. (getter + setter)

Events

  • message - Websocket received a message.
  • connected - Emitted whenever a connection gets re-established.
  • disconnected - Emitted whenever the pingTimeout threshold is exceeded, or a network error occurs.
  • killed - Emitted if .close() was called which prevents further connection re-establishment.

Readme

Keywords

Package Sidebar

Install

npm i graceful-ws

Weekly Downloads

14

Version

1.3.4

License

MIT

Unpacked Size

42.5 kB

Total Files

11

Last publish

Collaborators

  • simonwep