WebSocket is a communication protocol that provides full-duplex, persistent connections between client and server. Unlike HTTP where the client always initiates, WebSocket lets the server push data to the client in real time.

How WebSocket Works

HTTP is request-response: the client asks, the server answers, the connection closes. WebSocket upgrades an HTTP connection to a persistent, bidirectional channel. Both sides can send messages at any time without the overhead of new connections.

WebSocket is essential for real-time features: chat apps (Slack, Discord), live dashboards, collaborative editing (Google Docs), multiplayer games, and stock tickers. Libraries like Socket.IO (Node.js) and Pusher abstract the complexity.

Why Developers Use WebSocket

Use WebSocket when you need real-time, bidirectional communication. Chat systems, live notifications, collaborative editors, gaming, and financial tickers all rely on WebSocket connections for instant data delivery.

Key Concepts

  • Full-Duplex — Both client and server can send messages simultaneously — unlike HTTP's one-at-a-time request-response
  • Connection Upgrade — WebSocket starts as an HTTP request, then upgrades to a persistent ws:// or wss:// connection
  • Socket.IO — The most popular WebSocket library for Node.js — adds auto-reconnection, rooms, and fallback transports
  • Heartbeat — Periodic ping/pong messages that keep the connection alive and detect disconnections

WebSocket Client and Server

javascript
// Client
const ws = new WebSocket('wss://api.example.com/chat');
ws.onmessage = (event) => console.log('Received:', event.data);
ws.send(JSON.stringify({ type: 'message', text: 'Hello!' }));

// Server (Node.js with ws library)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    // Broadcast to all clients
    wss.clients.forEach(c => c.send(data));
  });
});

Frequently Asked Questions

When should I use WebSocket vs REST?

Use REST for standard CRUD operations where the client initiates all requests. Use WebSocket when you need the server to push updates in real-time — chat, notifications, live data feeds.

Is WebSocket secure?

Yes, use wss:// (WebSocket Secure) which runs over TLS, just like HTTPS. Never use unencrypted ws:// in production.