WebSocket vs HTTP: Key Differences Explained

WebSocket is a standardized communication protocol (RFC 6455) that enables full-duplex, bidirectional, real-time communication between a client (typically a web browser) and a server over a single, persistent TCP connection. Unlike the traditional HTTP request-response model (which is unidirectional and stateless), WebSocket eliminates the need for repeated HTTP polling or long-polling, drastically reducing latency and network overhead for real-time applications.

Core Mechanism

1. Handshake Process (Upgrade from HTTP)

WebSocket starts with an HTTP-based handshake to establish the persistent connection:

  1. Client Request: The client sends an HTTP GET request to the server with special headers to initiate the upgrade:httpGET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13
    • Upgrade: websocket: Signals the client’s desire to switch from HTTP to WebSocket.
    • Sec-WebSocket-Key: A random base64 string used for server authentication (prevents fake WebSocket requests).
  2. Server Response: If the server supports WebSocket, it responds with an HTTP 101 (Switching Protocols) status code:httpHTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
    • Sec-WebSocket-Accept: A hash of the client’s Sec-WebSocket-Key + a fixed GUID, proving the server understands WebSocket.
  3. Connection Established: After the handshake, the TCP connection is kept alive, and both parties can send data to each other at any time.

2. Data Transmission

  • Frames: Data is exchanged in small, lightweight frames (not HTTP packets) with minimal overhead (2-10 bytes per frame).
  • Binary/Text Support: WebSocket natively supports both UTF-8 text data (e.g., JSON messages) and binary data (e.g., images, audio streams).
  • Full-Duplex: Client and server can send data simultaneously (unlike HTTP, where the client must wait for a response after a request).

Key Characteristics

  1. Persistent Connection: A single TCP connection is maintained for the lifetime of the session (until closed by either party), avoiding the overhead of re-establishing connections for each message (a major issue with HTTP polling).
  2. Low Latency: Eliminates the latency of HTTP headers (which add ~800 bytes per request/response) and reduces round-trip time (RTT) for real-time data.
  3. Cross-Origin Support: Works with CORS (Cross-Origin Resource Sharing) headers, enabling communication between clients and servers on different domains (with proper server configuration).
  4. Stateful: The connection retains context between messages, so the server can associate messages with a specific client session (no need for cookies/tokens on every request).
  5. Fallback Options: Most WebSocket libraries (e.g., Socket.IO) include fallbacks (long-polling, server-sent events) for older browsers that do not support WebSocket natively.

Common Use Cases

WebSocket is essential for applications requiring real-time, bidirectional communication:

  • Chat Applications: Instant messaging (e.g., WhatsApp Web, Slack) where messages need to be delivered immediately.
  • Collaborative Tools: Real-time document editing (e.g., Google Docs), whiteboarding, or code collaboration.
  • Live Data Feeds: Stock tickers, sports scores, cryptocurrency prices, or IoT sensor data updates.
  • Gaming: Multiplayer browser games (real-time player movements, score updates).
  • Notifications: Push-style alerts (e.g., social media notifications, order status updates) without polling.

WebSocket vs. HTTP (Key Differences)

FeatureWebSocketHTTP
Connection TypePersistent, full-duplexStateless, request-response (half-duplex)
DirectionBidirectional (client ↔ server)Unidirectional (client → server, then server → client)
OverheadMinimal (frame headers)High (HTTP headers on every request)
LatencyVery low (real-time)High (delayed by polling/long-polling)
Use CaseReal-time communicationStatic content, REST API requests

Basic Code Example (JavaScript)

Client-Side (Browser)

javascript

运行

// Create a WebSocket connection
const socket = new WebSocket('ws://example.com/chat');

// Connection opened
socket.addEventListener('open', (event) => {
  socket.send('Hello Server!'); // Send message to server
});

// Listen for messages from server
socket.addEventListener('message', (event) => {
  console.log('Message from server:', event.data);
});

// Connection closed
socket.addEventListener('close', (event) => {
  console.log('WebSocket connection closed:', event.code, event.reason);
});

// Handle errors
socket.addEventListener('error', (error) => {
  console.error('WebSocket error:', error);
});

Server-Side (Node.js with ws library)

First, install the library:

bash

运行

npm install ws

Then the server code:

javascript

运行

const WebSocket = require('ws');

// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

// Listen for new client connections
wss.on('connection', (ws) => {
  console.log('New client connected');

  // Listen for messages from client
  ws.on('message', (data) => {
    console.log(`Received from client: ${data}`);
    // Send a response back to the client
    ws.send(`Server received: ${data}`);
    
    // Broadcast message to all connected clients (for chat apps)
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(`Broadcast: ${data}`);
      }
    });
  });

  // Listen for connection close
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

Limitations & Best Practices

Avoid sending large payloads; split big data into smaller frames to maintain low latency.

Limitations:

Firewall/Proxy Restrictions: Some corporate firewalls block WebSocket traffic (port 80/443 is safer than custom ports).

Connection Limits: Servers can handle thousands of WebSocket connections, but resource management (memory, file descriptors) is critical.

No Built-in Reconnection: Clients need custom logic to reconnect if the connection drops (libraries like Socket.IO handle this automatically).

Best Practices:

Use wss:// (WebSocket over TLS) instead of ws:// to encrypt traffic (prevents eavesdropping).

Implement heartbeats (ping/pong frames) to detect dead connections and keep them alive.



了解 Ruigu Electronic 的更多信息

订阅后即可通过电子邮件收到最新文章。

Posted in

Leave a comment