@proj-airi/better-ws provides runtime-agnostic WebSocket primitives designed for reliable real-time connections. It manages connection lifecycles, automatic reconnection, and server-side peer management (tracking, broadcasting, and grouping) without imposing a specific message protocol like JSON-RPC or an event system.
Use this library when you need connection lifecycle management, peer registries, and broadcast primitives, but want to maintain full control over your own message shapes or are building a custom protocol adapter on top.
import { createClient } from '@proj-airi/better-ws'
import { createServer } from '@proj-airi/better-ws/server'
// Basic Client
const client = createClient({
url: 'ws://localhost:3000/ws',
reconnect: {
retries: Number.POSITIVE_INFINITY,
delay: attempt => Math.min(1000 * 2 ** (attempt - 1), 30_000),
},
})
await client.connect()
client.send('hello')
// Basic Server
const server = createServer<string>()
server.onMessage(({ server, message }) => {
server.broadcast(message)
})
const peer = server.accept({
id: 'peer-1',
send(message) {
console.info('send to runtime', message)
return true
},
})
peer.receive('hello')