WebSocket

A protocol enabling full-duplex, real-time communication between client and server.

WebSocket is a communication protocol that provides full-duplex, bidirectional communication channels over a single TCP connection. Unlike HTTP, WebSocket allows both client and server to send messages at any time.

WebSocket vs HTTP

FeatureWebSocketHTTP
ConnectionPersistentRequest-Response
DirectionBidirectionalClient-initiated
OverheadLow (after handshake)Headers on every request
Real-timeYesPolling required

Use Cases

  • Chat Applications: Real-time messaging
  • Live Dashboards: Stock prices, analytics
  • Gaming: Multiplayer game state
  • Notifications: Push updates to clients
  • Collaborative Tools: Google Docs-style editing

Connection Lifecycle

  1. Handshake: HTTP upgrade request
  2. Open: Connection established
  3. Message: Data exchange
  4. Close: Connection terminated

Best Practices

  • Implement reconnection logic
  • Use heartbeat/ping-pong for connection health
  • Handle connection errors gracefully
  • Consider fallback to polling

Code Examples

Browser WebSocket

const ws = new WebSocket("wss://api.example.com/socket");

ws.onopen = () => {
  console.log("Connected");
  ws.send(JSON.stringify({ type: "subscribe", channel: "updates" }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log("Received:", data);
};

ws.onclose = () => console.log("Disconnected");