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

reevsocket

v1.0.5

Published

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.

Downloads

18

Readme

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:

| Option | Type | Default | Description | |---------------------|------------|------------|--------------------------------------------------------------------------------------------------------------------------| | maxAttempts | number | Infinity | Maximum number of reconnection attempts. | | delay | number | 10000 | Time between reconnection attempts in milliseconds. | | exponentialFactor | number | 0 | Exponential backoff factor for reconnection attempts. A value of 0 indicates no exponential backoff. | | maxDelay | number | 30000 | Maximum delay between reconnection attempts in milliseconds, applicable when exponential backoff is used. | | heartbeatInterval | number | 150000 | Interval in milliseconds for sending heartbeat messages. If not specified, the default value is used. | | disableHeartbeat | boolean | false | If true, heartbeat messages are not sent. | | pongTimeoutInterval| number | 30000 | Timeout in milliseconds for expecting a pong response after a heartbeat message. Default is based on heartbeatInterval. | | onConnect | function | None | Callback function invoked when a connection is successfully established. | | onClose | function | None | Callback function invoked when the connection is closed. | | onMessage | function | None | Callback function invoked when a message is received. | | onError | function | None | Callback function invoked when an error occurs. | | onReconnecting | function | None | Callback function invoked during a reconnection attempt. | | onOverflow | function | None | Callback function invoked when the maximum number of reconnection attempts is exceeded. | | protocols | string[] | None | Optional protocols for the WebSocket connection. Either a single protocol string or an array of protocol strings. | | metadata | object | null | Passes metadata on every event object. | | enableAcknowledge | boolean | false | Sends acknowledge event back on successfully recieving the event | | handleApiGatewayDefaults | boolean | false | Handles the 10 mins idle timeout + 2 hours connection duration for WebSocket API |

send(data)

It is a native to [WebSocket.send()][send(data)]

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()][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()][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.