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

ws-events-handler

v1.0.6

Published

The WebSocketEventsHandler class is a comprehensive JavaScript handler for managing WebSocket connections, including automatic reconnection, heartbeat management, event handling, and offline event storage. This class provides robust support for WebSocket

Downloads

403

Readme

WebSocketEventsHandler

The WebSocketEventsHandler class is a comprehensive JavaScript handler for managing WebSocket connections, including automatic reconnection, heartbeat management, event handling, and offline event storage. This class provides robust support for WebSocket applications, ensuring seamless communication even in unstable network environments.

Features

  • Automatic Reconnection: Attempts to reconnect with exponential backoff if the connection drops.
  • Heartbeat Support: Regularly pings the server to maintain connection, with configurable intervals and timeouts.
  • Event Handling: Allows registration of custom event handlers and triggers them on incoming messages.
  • Local Event Storage: Caches events when offline and dispatches them once reconnected.
  • Debug Mode: Logs detailed information about the WebSocket connection and events for troubleshooting.
  • Network Detection: Listens for network status changes to handle online and offline events.

Installation

Install this module via npm:

npm install ws-events-handler

Usage

Basic Initialization

import WebSocketEventsHandler from './WebSocketEventsHandler';

const wsHandler = new WebSocketEventsHandler('ws://your-websocket-url', {
  heartbeat: { 
    interval: 15000, 
    message: 'ping', 
    expectedResponse: 'pong', 
    timeout: 10000 
  },
  connection: { 
    maxRetries: 5, 
    retryDelay: 1000 
  },
  debug: true
});

Configuration Options

  • heartbeat (object):

    • interval: Interval between heartbeats in milliseconds.
    • message: Message sent as heartbeat.
    • expectedResponse: Expected response from server.
    • timeout: Time to wait for a response before reconnecting.
  • connection (object):

    • maxRetries: Maximum number of reconnection attempts.
    • retryDelay: Delay between reconnection attempts.
    • fallback.localEvents: Enable storing events locally when offline.
  • debug (boolean): Enable verbose logging.

Event Handling

Register an event handler for a specific event:

wsHandler.on('eventName', (data) => {
  console.log('Event received:', data);
});

Cyclic event handling

Register an event handler for a specific event in cycles.

  wsEvents.on('eventName', { 
    cycle: { 
      every: 3,
      exclusive: true,
      once: true,
      callback: (data) => {
        console.log(data);
      }
    },
    callback: (data) => {
      console.log("this won't fire as cycle is configured to be exclusive.")
    }
  })

This configuration will fire callback once 3 messages for 'eventName' have arrived.

Configuration options for cycles

  • every: Cycle will be executed every N messages.
  • exclusive: Cycle will only execute it's internal callback and not the root callback defined in the handler configuration. If false, root callback will be called every time a message arrives to 'eventName'.
  • rounds: Cycle will run N times and then it will self-destruct.
  • once: Cycle will run only once. (similar to setting rounds = 1)

Unregister an event:

wsHandler.off('eventName');

Sending Events

To send an event with optional payload:

wsHandler.send('eventName', { key: 'value' });

Destroying the WebSocket Connection

To clean up resources and close the WebSocket connection:

wsHandler.destroy('Reason for destruction');

Methods

  • on(eventName, config): Registers an event handler.
  • off(eventName): Unregisters an event handler.
  • send(eventName, payload): Sends an event with an optional payload.
  • destroy(reason): Destroys the WebSocket connection and cleans up resources.

License

This project is licensed under the MIT License.