WebSockets Cheat Sheet
Quick reference for opening, sending, and closing full-duplex WebSocket connections between browser and server, including lifecycle events and reconnection.
2 PagesIntermediateMar 2, 2026
Client-Side WebSocket API
Opening a connection and handling core events.
javascript
// Create connectionconst socket = new WebSocket('wss://example.com/socket');socket.addEventListener('open', () => { console.log('Connected'); socket.send('Hello Server!');});socket.addEventListener('message', (event) => { console.log('Received:', event.data);});socket.addEventListener('close', (event) => { console.log('Closed:', event.code, event.reason);});socket.addEventListener('error', (event) => { console.error('WebSocket error:', event);});// Send JSONsocket.send(JSON.stringify({ type: 'chat', text: 'hi' }));// Close gracefullysocket.close(1000, 'Done');
Node.js WebSocket Server (ws)
Accepting connections and broadcasting messages.
javascript
const { WebSocketServer } = require('ws');const wss = new WebSocketServer({ port: 8080 });wss.on('connection', (ws, req) => { console.log('Client connected:', req.socket.remoteAddress); ws.on('message', (data) => { // Broadcast to all connected clients wss.clients.forEach((client) => { if (client.readyState === ws.OPEN) { client.send(data.toString()); } }); }); ws.on('close', () => console.log('Client disconnected')); ws.ping(); // heartbeat frame});
readyState Values
The four states a WebSocket connection moves through.
- CONNECTING (0)- Socket created, connection not yet open
- OPEN (1)- Connection is open and ready to send/receive
- CLOSING (2)- Connection handshake for closing is in progress
- CLOSED (3)- Connection is closed or failed to open
- socket.readyState- Property on the WebSocket instance exposing the current state as a number
Common Close Codes
Status codes sent in the close frame.
- 1000- Normal closure, purpose fulfilled
- 1001- Going away (e.g. page navigating away, server shutting down)
- 1006- Abnormal closure; no close frame was received (connection dropped)
- 1008- Policy violation (generic rejection)
- 1011- Server encountered an unexpected internal error
- 4000-4999- Reserved range for application-defined custom codes
Pro Tip
Implement heartbeat ping/pong frames and exponential-backoff reconnect logic on the client — WebSocket connections silently die behind proxies and load balancers without periodic keepalive traffic.
Was this cheat sheet helpful?
Explore Topics
#WebSockets#WebSocketsCheatSheet#WebDevelopment#Intermediate#Client#Side#WebSocket#API#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance