StreetJS includes a bounded WebSocket server built on the ws library. It enforces a maximum connection count, sends periodic heartbeats to detect dead connections, and exposes a typed event emitter API.
import'reflect-metadata';import{streetApp,StreetWebSocketServer,StreetSocket,container,TelemetryTracker,}from'streetjs';constapp=streetApp({port:3000});constwss=newStreetWebSocketServer({heartbeatIntervalMs:30_000,// ping every 30smaxConnections:10_000,// reject with 1013 when exceeded});container.register(StreetWebSocketServer,wss);// Handle new connectionswss.on('connection',(socket:StreetSocket)=>{console.log('Client connected');socket.on('message',(data:unknown)=>{console.log('Received:',data);socket.emit('echo',data);});socket.on('close',()=>{console.log('Client disconnected');});});awaitapp.listen();
StreetSocket API
Each connected client is represented by a StreetSocket instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Send a typed event to this clientsocket.emit('eventName',payload);// Listen for events from this clientsocket.on('eventName',(data:unknown)=>{/* ... */});// Remove a listenersocket.off('eventName',handler);// Check if socket is still openif (!socket.closed){socket.emit('update',{ts:Date.now()});}// Close the connectionsocket.close(1000,'Normal closure');
Broadcasting
Send a message to all connected clients:
1
2
3
4
5
6
7
8
9
// Broadcast to all clientswss.broadcast('announcement',{text:'Server restarting in 60s'});// Broadcast to a subset (manual filter)for (constsocketofwss.clients){if (socket.userId===targetUserId){socket.emit('notification',{message:'You have a new message'});}}
// Current connection countconsole.log(wss.connectionCount);// All active socketsfor (constsocketofwss.clients){console.log(socket.closed?'dead':'alive');}
Graceful shutdown
1
2
3
4
5
process.once('SIGTERM',async ()=>{awaitwss.close();// closes all connections, stops accepting new onesawaitpool.close();process.exit(0);});
Server-Sent Events (SSE)
For one-way server-to-client streaming, use SSE instead of WebSockets: