WebSocket is a communication protocol defined in RFC 6455 that enables full-duplex, bidirectional communication over a single TCP connection. Unlike HTTP's request-response model, WebSocket maintains a persistent connection where both client and server can push messages independently, making it ideal for real-time applications like chat systems, live dashboards, collaborative editing, and multiplayer gaming. The protocol starts with an HTTP upgrade handshake, transitions to a framing-based message exchange, and remains open until explicitly closed. One key consideration: WebSocket connections are stateful and long-lived, requiring careful design for scalability, authentication, reconnection, and resource management — especially when handling thousands of concurrent connections across distributed servers.
What This Cheat Sheet Covers
This topic spans 25 focused tables and 173 indexed concepts. Below is a complete table-by-table outline of this topic, spanning foundational concepts through advanced details.
Table 1: Protocol Fundamentals
| Concept | Example | Description |
|---|---|---|
wss://example.com/chatwss://example.com/updates | • Standard defining WebSocket communication • wss is the recommended TLS-secured scheme for production deployments. | |
GET /chat HTTP/1.1Upgrade: websocketConnection: UpgradeSec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== | • HTTP upgrade request • client sends Sec-WebSocket-Key, server responds with 101 Switching Protocols. | |
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= | • Server's response header • computed from client's key using SHA-1 hash to confirm handshake. | |
ws.send("Hello")ws.onmessage = (e) => {...} | Both client and server can send messages at any time without polling. | |
Connection remains open until closed | • Eliminates HTTP overhead of repeated handshakes • reduces latency for real-time data. |