2.0.0 • Published 11 months ago

@jotter/websocket v2.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

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.

proptypedefaultdescription
enabledbooleantrueWhether to automatically reconnect
maxAttemptsnumber | (attempt)=>number10Maximum number of reconnection attempts
delaynumber1000Reconnection delay (ms)
shouldReconnect(event, ctx) => booleanUser-defined reconnection rules

ping

Keep-alive (Ping) configuration.

proptypedefaultdescription
enabledbooleantrueWhether to send keep-alive (Ping)
intervalnumber30000Keep-alive (Ping) interval (ms)
messageany'ping'Keep-alive (Ping) message

messageQueue

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

proptypedefaultdescription
enabledbooleantrueWhether to enable message queue
maxnumber100Maximum 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.

2.0.0

11 months ago

1.2.5

2 years ago

1.2.4

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.1

2 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago