What is WebSocket?

The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment and a remote host. It provides a full-duplex communication channel over a single TCP connection and is designed to work over HTTP ports 80 and 443.

Key Features

Full-Duplex

Simultaneous bidirectional communication between client and server.

Low Overhead

Minimal framing overhead compared to HTTP polling.

Real-Time

Instant message delivery without polling delays.

Firewall Friendly

Works through HTTP ports and proxy servers.

WebSocket Handshake

1. Client Request

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

2. Server Response

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

WebSocket Frame Format

Frame Header

FIN: Final fragment flag
Opcode: Frame type (text, binary, close, etc.)
MASK: Masking flag
Payload Length: Data length

Frame Types

0x1: Text frame
0x2: Binary frame
0x8: Close frame
0x9: Ping frame
0xA: Pong frame

Security Features

  • Origin Validation: Server can validate the origin of WebSocket requests
  • Masking: Client-to-server frames are masked to prevent cache poisoning
  • TLS Support: WebSocket Secure (WSS) provides encryption
  • Same-Origin Policy: Browser enforces origin restrictions
  • Subprotocol Negotiation: Application-level protocol selection

Connection Management

Opening

HTTP upgrade handshake establishes WebSocket connection.

Data Transfer

Bidirectional message exchange using WebSocket frames.

Ping/Pong

Keepalive mechanism to detect connection failures.

Closing

Graceful connection termination with close frames.

Common Applications

  • Real-Time Chat: Instant messaging applications
  • Live Updates: Social media feeds and notifications
  • Gaming: Multiplayer online games
  • Trading Platforms: Real-time financial data
  • Collaborative Editing: Google Docs-style applications
  • IoT Dashboards: Real-time sensor data visualization
  • Video Streaming: Live video chat and streaming
  • Remote Desktop: Screen sharing applications

Advantages over HTTP Polling

Lower Latency

No need to establish new connections for each message.

Reduced Overhead

Minimal frame headers vs. full HTTP headers.

Server Push

Server can initiate communication without client request.

Resource Efficiency

Single persistent connection vs. multiple HTTP requests.

Additional Resources