typescriptintermediate
WebSocket Server with ws
Create a WebSocket server with connection tracking, heartbeat ping/pong, and typed message handling.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { WebSocketServer, WebSocket } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
const clients = new Set<WebSocket>();
wss.on('connection', (ws) => {
clients.add(ws);
console.log(`Client connected (${clients.size} total)`);
ws.on('message', (raw) => {
const msg = JSON.parse(raw.toString());
// Broadcast to all other clients
for (const client of clients) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg));
}
}
});
ws.on('close', () => {
clients.delete(ws);
});
// Heartbeat
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) ws.ping();
}, 30_000);
ws.on('close', () => clearInterval(interval));
});Use Cases
- Chat applications
- Live notifications
- Real-time dashboards
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonadvanced
OpenAI Realtime API WebSocket
Connect to the OpenAI Realtime API via WebSocket for low-latency voice and text streaming.
Best for: voice AI
#openai#realtime
typescriptadvanced
Graceful Server Shutdown
Handle SIGTERM and SIGINT signals to drain connections, close database pools, and exit cleanly.
Best for: Production server deployment
#server#shutdown
typescriptbeginner
Native HTTP Server
Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.
Best for: Lightweight API server without frameworks
#nodejs#http
typescriptbeginner
Fastify Server Setup
Create a high-performance Fastify server with schema validation, plugins, and typed routes.
Best for: High-performance REST APIs
#nodejs#fastify