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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@toolcore/websocket

v1.0.2

Published

A reconnected websocket

Downloads

12

Readme

WebSocket Manager

A robust WebSocket connection manager with automatic reconnection, message queuing, and event handling capabilities.

Features

  • 🔄 Automatic Reconnection: Handles connection drops with configurable retry logic
  • 📨 Message Queueing: Stores messages when offline and sends them when reconnected
  • Exponential Backoff: Smart reconnection timing with configurable delays
  • 🎯 TypeScript Support: Fully typed for better development experience
  • 🔧 Configurable: Extensive options for customizing behavior
  • 📊 State Management: Track connection state with enum values
  • 🎪 Event System: Flexible event listeners for all WebSocket events

Installation

npm install @toolcore/websocket

Quick Start

import { WebSocketManager, WebSocketState } from '@toolcore/websocket';

// Create a new instance
const wsManager = new WebSocketManager({
  debug: true,
  maxRetries: 5
});

// Connect to a server
wsManager.connect('wss://echo.websocket.org');

// Listen for events
wsManager.onopen((event) => {
  console.log('Connected to server');
});

wsManager.onmessage((event) => {
  console.log('Received message:', event.data);
});

wsManager.onclose((event) => {
  console.log('Connection closed:', event.code, event.reason);
});

// Send a message
wsManager.send('Hello, Server!');

API Documentation

Constructor

const wsManager = new WebSocketManager(options?: Options);

Methods

connect(url: string, protocols?: string | string[]): void

Establishes a connection to the WebSocket server.

wsManager.connect('wss://api.example.com/socket');
wsManager.connect('wss://api.example.com/socket', 'protocol-v1');

close(code?: number, reason?: string): void

Closes the connection and stops reconnection attempts.

wsManager.close(1000, 'Normal closure');

send(data: any): void

Sends data through the WebSocket connection. If not connected, the message is queued.

wsManager.send('String message');
wsManager.send({ type: 'chat', content: 'Hello' });

Event Listeners

// Connection opened
wsManager.onopen((event: Event) => {
  console.log('Connection established');
});

// Connection closed
wsManager.onclose((event: CloseEvent) => {
  console.log('Connection closed', event.code, event.reason);
});

// Error occurred
wsManager.onerror((event: Event) => {
  console.error('WebSocket error', event);
});

// Message received
wsManager.onmessage((event: MessageEvent) => {
  console.log('Message received:', event.data);
});

// Generic event listener
wsManager.addEventListener('message', (event: MessageEvent) => {
  // Handle message
});

// Remove event listener
wsManager.removeEventListener('message', callback);

State Management

// Get current state
const state = wsManager.getState();

// Check if connected
const isConnected = wsManager.isConnected();

if (isConnected) {
  console.log('WebSocket is ready for messages');
}

Configuration Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | maxReconnectionDelay | number | 10000 | Maximum delay between reconnection attempts (ms) | | minReconnectionDelay | number | 1000 | Minimum delay between reconnection attempts (ms) | | reconnectionDelayGrowFactor | number | 1.3 | Multiplier for exponential backoff | | minUptime | number | 5000 | Minimum connection time before resetting retry count (ms) | | connectionTimeout | number | 4000 | Timeout for initial connection (ms) | | maxRetries | number | Infinity | Maximum number of reconnection attempts | | maxEnqueuedMessages | number | 100 | Maximum number of messages to queue when offline | | debug | boolean | false | Enable debug logging |

WebSocket States

enum WebSocketState {
  CONNECTING,    // Connection is being established
  OPEN,          // Connection is open and ready
  CLOSING,       // Connection is in the process of closing
  CLOSED,        // Connection is closed or couldn't be opened
  RECONNECTING   // Attempting to reconnect after connection loss
}

Advanced Usage

Custom Reconnection Logic

const wsManager = new WebSocketManager({
  minReconnectionDelay: 2000,
  maxReconnectionDelay: 30000,
  reconnectionDelayGrowFactor: 2,
  maxRetries: 10,
  connectionTimeout: 10000
});

Handling Different Message Types

wsManager.onmessage((event: MessageEvent) => {
  try {
    const data = JSON.parse(event.data);
    
    switch (data.type) {
      case 'chat':
        handleChatMessage(data);
        break;
      case 'notification':
        handleNotification(data);
        break;
      default:
        console.log('Unknown message type:', data.type);
    }
  } catch (error) {
    console.log('Raw message:', event.data);
  }
});

Connection State Monitoring

// Monitor connection state changes
let previousState = wsManager.getState();

setInterval(() => {
  const currentState = wsManager.getState();
  
  if (currentState !== previousState) {
    console.log('State changed:', WebSocketState[previousState], '->', WebSocketState[currentState]);
    previousState = currentState;
  }
}, 1000);

Error Handling

wsManager.onerror((event: Event) => {
  console.error('WebSocket error occurred');
  // Handle error appropriately
});

wsManager.addEventListener('error', (event: Event) => {
  // Alternative way to listen for errors
});

Browser Support

This library supports all modern browsers that implement the WebSocket API:

  • Chrome 16+
  • Firefox 11+
  • Safari 7+
  • Edge 12+
  • Internet Explorer 10+

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.