WebSocket Server With Heartbeat
Implement a WebSocket server with heartbeat ping pong timeout and broadcast for real-time communication.
Code
import{WebSocketServer}from'ws';export function createWSServer({port=8080,heartbeatInterval=30000,heartbeatTimeout=10000}={}){const wss=new WebSocketServer({port});const clients=new Set();wss.on('connection',(ws)=>{clients.add(ws);ws.isAlive=true;ws.on('pong',()=>ws.isAlive=true);ws.on('close',()=>clients.delete(ws));});const heartbeat=setInterval(()=>{for(const ws of clients){if(!ws.isAlive){ws.terminate();clients.delete(ws);continue;}ws.isAlive=false;ws.ping();}},heartbeatInterval);function broadcast(message){const data=JSON.stringify(message);for(const ws of clients)if(ws.readyState===ws.OPEN)ws.send(data);}return{wss,broadcast,close:()=>{clearInterval(heartbeat);wss.close();}};}What the code does
Count the functions createWSServer and broadcast as the entire surface area of WebSocket Server With Heartbeat.
WebSocketServer are the only symbols borrowed from ws — the coupling is explicit and narrow.
Watch out for
- Dependency check:
ws— not built-in, must be present in the project.
Applying it
The main signature reads export function createWSServer({port=8080,heartbeatInterval=30000,heartbeatTimeout=10000}={})
createWSServer is what another module would consume; nothing else here is load-bearing for callers.
FAQ
- Do I need to install anything before running this?
- Yes: `ws` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.