Skip to content

๐Ÿ”Œ Graceful WebSocket wrapper with connection re-establishment capabilities.

License

Notifications You must be signed in to change notification settings

simonwep/graceful-ws

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

68 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

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.

About

๐Ÿ”Œ Graceful WebSocket wrapper with connection re-establishment capabilities.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published