Modern and useful WebSocket API wrapper class with additional features such as auto-reconnect, message queuing and Keep-alive detection.
标准且实用的 WebSocket 包装器,具有标准 WebSocket API
。支持心跳检测,异常消息处理和自动重连机制。
- ⏰ With Standard WebSocket API
- 🧬 Automatic Reconnection
- 💓 Keep-alive (Ping) Support
- 📮 Message Queuing
- 🌐 Flexible Configuration
npm
npm install @jotter/websocket
browser
https://cdn.jsdelivr.net/npm/@jotter/websocket/dist/index.min.js
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'],
})
new WebSocketConnect(
url: string,
protocols?: string | string[],
options?: IOptions
)
WebSocket connection Url.
- Type:
string
WebSocket connection protocol.
- Type:
string | string[]
WebSocket connection options.
interface IOptions {
// 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[]
}
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 |
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 |
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 |
send(data: any)
: Send a messageclose(code?: number, reason?: string)
: Close the connection
open
: Connection establishedclose
: Connection closedmessage
: Message receivederror
: Connection errorconnecting
: Connection is being establishedreconnect
: Reconnection attemptreconnectend
: Reconnection attempts ended
url
: WebSocket URLreadyState
: Current connection stateprotocol
: Negotiated protocolbufferedAmount
: Number of bytes queuedbinaryType
: Binary data typeextensions
: Negotiated extensions
Supports all modern browsers with WebSocket API support.
MIT License
Contributions are welcome! Please feel free to submit a Pull Request.