Skip to content

WebSockets: Real-Time Bidirectional Communication

WebSockets: Real-Time Bidirectional Communication

The WebSocket protocol provides a full-duplex communication channel over a single, long-lived TCP connection. Unlike HTTP, which is request-response based, WebSockets allow both the client and server to send data at any time.

🏗️ How it Works: The Handshake

A WebSocket connection starts as a standard HTTP request with an Upgrade header.

  1. Client Request:
    GET /chat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
  2. Server Response (101 Switching Protocols):
    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade

Once the handshake is complete, the TCP connection remains open for binary or text frames.


🚀 Key Features

  • Full-Duplex: Simultaneous bidirectional data flow.
  • Low Overhead: After the initial handshake, message frames have very small headers (2-14 bytes) compared to HTTP.
  • Stateful: The server knows which clients are connected without needing session cookies in every frame.

🛠️ Implementation Example (JavaScript)

Client Side

const socket = new WebSocket('ws://example.com/socket');

socket.onopen = () => {
    console.log('Connected!');
    socket.send(JSON.stringify({ type: 'greet', msg: 'Hello Server!' }));
};

socket.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Message from server:', data);
};

📊 WebSockets vs. Other Tech

TechnologyDirectionBest For
WebSocketsBidirectionalChat, Games, Financial tickers.
SSE (Server-Sent Events)Server -> ClientLive news feeds, Social media notifications.
Long PollingBidirectional (Simulated)Legacy browser support.

💡 Best Practices & Security

  • Heartbeats (Pings/Pongs): Periodically send small packets to keep the connection alive and detect dead clients.
  • Horizontal Scaling: Use a Pub/Sub system (like Redis) to broadcast messages across multiple server instances.
  • Authentication: Authenticate during the initial HTTP handshake before upgrading the connection.
  • WSS (Secure): Always use wss:// (WebSocket over TLS) in production.