1.0.5 • Published 2 months ago

reevsocket v1.0.5

Weekly downloads
-
License
ISC
Repository
github
Last release
2 months ago

ReEvSocket

ReEvSocket is a small wrapper around WebSocket which helps you in building event based socket requirement and will also automatically reconnect if the connect is lost. This module provides a comprehensive solution for managing WebSocket connections, including automatic retries, heartbeat for connection health, and event handling. It's designed to ensure persistent and reliable connections, making it especially useful for applications that require constant data exchange over WebSockets.

Install

$ npm install --save reevsocket

Features

  • Automatic Reconnection: Supports automatic reconnection with configurable delay and maximum attempts.
  • Exponential Backoff: Option to use exponential backoff strategy for reconnection attempts.
  • Heartbeat: Sends periodic "ping" messages to check connection health and automatically reconnects if the connection is lost.
  • Event Handling: Simplified event subscription to handle incoming messages and WebSocket events (open, close, error).
  • Extensible: Supports custom protocols and allows passing additional options for WebSocket initialization.

Usage

const ReEvSocket = require('reevsocket');

const ws = new ReEvSocket('ws://localhost:3000', {
  delay: 10000, // Time between reconnection attempts
  maxAttempts: 10, // Maximum number of reconnection attempts
  exponentialFactor: 2, // Exponential backoff factor
  maxDelay: 30000, // Maximum delay for reconnection attempts
  heartbeatInterval: 30000, // Interval for sending heartbeat messages
  disableHeartbeat: false, // Set to true to disable heartbeat messages
  pongTimeoutInterval: 35000, // Timeout interval for expecting pong response
  metadata: { "client_id": "123-ABC" }, // pass some metadata on every heartbeat
  enableAcknowledge: true, // send acknowledge of the recieved action
  onConnect: e => console.log('Connected!', e),
  onMessage: e => console.log('Ring Ring:', e),
  onReconnecting: e => console.log('Trying to reconnect', e),
  onOverflow: e => console.log('Retry attemps exhausted :(', e),
  onClose: e => console.log('Closed!', e),
  onError: e => console.log('Error:', e)
});

/** Emit events, ws.emit(action, payload) */
ws.emit("my_event", { myKey: myVal })

/** Catch events */
ws.on("my_event", function (payload) {
  console.log(payload);   
});

API

ReEvSocket(url, options)

url

Type: String

The URL you want to connect to Should be prefixed with ws:// or wss://. This is passed directly to WebSocket.

options

Type: Object

Configuration Options

The WebSocket Connection Manager accepts an options object for configuration. Below is a table describing each available option:

OptionTypeDefaultDescription
maxAttemptsnumberInfinityMaximum number of reconnection attempts.
delaynumber10000Time between reconnection attempts in milliseconds.
exponentialFactornumber0Exponential backoff factor for reconnection attempts. A value of 0 indicates no exponential backoff.
maxDelaynumber30000Maximum delay between reconnection attempts in milliseconds, applicable when exponential backoff is used.
heartbeatIntervalnumber150000Interval in milliseconds for sending heartbeat messages. If not specified, the default value is used.
disableHeartbeatbooleanfalseIf true, heartbeat messages are not sent.
pongTimeoutIntervalnumber30000Timeout in milliseconds for expecting a pong response after a heartbeat message. Default is based on heartbeatInterval.
onConnectfunctionNoneCallback function invoked when a connection is successfully established.
onClosefunctionNoneCallback function invoked when the connection is closed.
onMessagefunctionNoneCallback function invoked when a message is received.
onErrorfunctionNoneCallback function invoked when an error occurs.
onReconnectingfunctionNoneCallback function invoked during a reconnection attempt.
onOverflowfunctionNoneCallback function invoked when the maximum number of reconnection attempts is exceeded.
protocolsstring[]NoneOptional protocols for the WebSocket connection. Either a single protocol string or an array of protocol strings.
metadataobjectnullPasses metadata on every event object.
enableAcknowledgebooleanfalseSends acknowledge event back on successfully recieving the event
handleApiGatewayDefaultsbooleanfalseHandles the 10 mins idle timeout + 2 hours connection duration for WebSocket API

send(data)

It is a native to WebSocket.send()

NOTE: Does not pass metadata if you use this method

on(event, listener)

Registers an event listener for a custom event.

  • event: Name of the event.
  • listener: Callback function to be executed when the event occurs.

Example for emitting events from external sources like API Gateway

import { ApiGatewayManagementApiClient, PostToConnectionCommand } from "@aws-sdk/client-apigatewaymanagementapi";

const client = new ApiGatewayManagementApiClient({ endpoint, region });

const requestParams = {
  ConnectionId: connectionId,
  Data: { "action": "my_custom_event", "payload": "HELLO WORLD" },
};

const command = new PostToConnectionCommand(requestParams);
await client.send(command);

Example for catching events at the client end

ws.on("my_custom_event", function (payload) { 
  // ... perform operation
  console.log(payload) // prints HELLO WORLD
})

emit(action, json)

Helps in emitting event based messages

Example:

ws.emit("my_custom_event", { message: "HELLO WORLD" })

close(code, reason)

It is native to WebSocket.close().

Note: The code will default to 1000 unless specified.

json(obj)

Convenience method that passes your obj (Object) through JSON.stringify before passing it to WebSocket.send().

retry()

If options.maxAttempts has not been exceeded, enqueues a reconnection attempt. Otherwise, it runs your options.onOverflow callback.

setMetadata()

Set or overwrite metadata which will be submitted on every event

Note: Metadata will be passed on every heartbeat event as well.

start()

Initializes a new WebSocket used on initialization and by retry().

isConnected()

Returns a boolean true or false.

Network Change Detection Experimental

This module automatically detects network changes (online/offline events) in browser environments and adjusts the WebSocket connection accordingly.

Note

This module is designed for Node.js and browser environments that support the Websocket API. Ensure that your target environment is compatible with WebSockets.

1.0.5

2 months ago

1.0.4

2 months ago

1.0.3

2 months ago

1.0.2

2 months ago

1.0.1

2 months ago

1.0.0

2 months ago

0.0.5

2 months ago

0.0.4

2 months ago

0.0.3

3 months ago

0.0.2

3 months ago

0.0.1

3 months ago