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();}};}Report a problem with this exampleOpens a pre-filled issue on GitHub.