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

@jotter/websocket

v2.0.0

Published

Modern and useful WebSocket API wrapper class with additional features such as auto-reconnect, message queuing and Keep-alive detection.

Downloads

85

Readme

WebSocketConnect

version CI status codecov downloads size browsers

Modern and useful WebSocket API wrapper class with additional features such as auto-reconnect, message queuing and Keep-alive detection.

标准且实用的 WebSocket 包装器,具有标准 WebSocket API。支持心跳检测,异常消息处理和自动重连机制。

Features

  • ⏰ With Standard WebSocket API
  • 🧬 Automatic Reconnection
  • 💓 Keep-alive (Ping) Support
  • 📮 Message Queuing
  • 🌐 Flexible Configuration

Installation

npm

npm install @jotter/websocket

browser

https://cdn.jsdelivr.net/npm/@jotter/websocket/dist/index.min.js

Usage

Fully compatible with the WebSocket API, for specific usage, please refer to: MDN WebSocket API

Basic:

import WebSocketConnect from '@jotter/websocket'

// Basic WebSocket connection
const ws = new WebSocketConnect('wss://example.com/')

// Event listeners
ws.addEventListener('open', (event) => {
	console.log('Connection established')
	ws.send('Hello, server!')
})

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

// Send text
ws.send('Hello, world!')

// Send JSON
ws.send({ type: 'message', content: 'Hello' })

// Send binary data
ws.send(new ArrayBuffer(8))

Advanced:

const ws = new WebSocketConnect('wss://example.com/', {
	// Reconnection options
	reconnect: {
		enabled: true,
		maxAttempts: 5,
		delay: (attempt) => Math.min(2000 * Math.pow(1.2, attempt), 30000),
	},

	// Ping (Keep-alive) options
	ping: {
		enabled: true,
		interval: 3000,
		message: 'ping',
	},

	// Message queue options
	messageQueue: 100,

	// Optional WebSocket protocols
	protocols: ['chat', 'json'],
})

API

Constructor

new WebSocketConnect(
  url: string,
  protocols?: string | string[],
  options?: IOptions
)

url

WebSocket connection Url.

  • Type: string

protocols

WebSocket connection protocol.

  • Type: string | string[]

Options

WebSocket connection options.

interface WebSocketConnectOptions {
	// Reconnection configuration
	reconnect?:
		| boolean
		| {
				enabled?: boolean
				maxAttempts?: number
				delay?: number | ((attempt: number) => number)
				shouldReconnect?: (event: CloseEvent, context: any) => boolean
		  }

	// Keep-alive (Ping) configuration
	ping?:
		| boolean
		| {
				enabled?: boolean
				interval?: number
				message?: any
		  }

	// Message queue configuration (Storing Unsent Messages)
	messageQueue?:
		| boolean
		| number
		| {
				enabled?: boolean
				max?: number
		  }

	// WebSocket protocols
	protocols?: string | string[]
}

reconnect

Reconnection configuration.

| prop | type | default | description | | --------------- | --------------------------- | ------- | --------------------------------------- | | enabled | boolean | true | Whether to automatically reconnect | | maxAttempts | number | (attempt)=>number | 10 | Maximum number of reconnection attempts | | delay | number | 1000 | Reconnection delay (ms) | | shouldReconnect | (event, ctx) => boolean | | User-defined reconnection rules |

ping

Keep-alive (Ping) configuration.

| prop | type | default | description | | -------- | ------- | ------- | --------------------------------- | | enabled | boolean | true | Whether to send keep-alive (Ping) | | interval | number | 30000 | Keep-alive (Ping) interval (ms) | | message | any | 'ping' | Keep-alive (Ping) message |

messageQueue

Message queue configuration. (Accumulated unsent-messages are sent when the connection is successful)

| prop | type | default | description | | ------- | ------- | ------- | --------------------------------------- | | enabled | boolean | true | Whether to enable message queue | | max | number | 100 | Maximum number of messages in the queue |

Methods

  • send(data: any): Send a message
  • close(code?: number, reason?: string): Close the connection

Events

  • open: Connection established
  • close: Connection closed
  • message: Message received
  • error: Connection error
  • connecting: Connection is being established
  • reconnect: Reconnection attempt
  • reconnectend: Reconnection attempts ended

Properties

  • url: WebSocket URL
  • readyState: Current connection state
  • protocol: Negotiated protocol
  • bufferedAmount: Number of bytes queued
  • binaryType: Binary data type
  • extensions: Negotiated extensions

Browser Compatibility

Supports all modern browsers with WebSocket API support.

License

MIT License

Contributing

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