WebSocket Connection Flow
WebSocket is a full-duplex communication protocol (RFC 6455) that upgrades an HTTP connection into a persistent, bidirectional channel, enabling either the client or server to push messages at any time without polling.
WebSocket is a full-duplex communication protocol (RFC 6455) that upgrades an HTTP connection into a persistent, bidirectional channel, enabling either the client or server to push messages at any time without polling.
Traditional HTTP is request/response: the client must initiate every exchange. WebSocket removes this constraint, making it the standard choice for real-time features like chat, live notifications, collaborative editing, and financial data feeds.
HTTP Upgrade Handshake: WebSocket begins as a standard HTTP/1.1 request. The client sends an Upgrade: websocket header along with Connection: Upgrade, a Sec-WebSocket-Key (a base64-encoded random value), and the protocol version. This reuses the existing TCP (and optionally TLS) connection — no new transport-layer handshake is needed.
101 Switching Protocols: The server accepts the upgrade by responding with HTTP 101 Switching Protocols, Upgrade: websocket, and a Sec-WebSocket-Accept value derived from the client's key via SHA-1. This handshake serves as a proof-of-intent, preventing non-WebSocket servers from accidentally accepting WebSocket connections.
Full-Duplex Messaging: Once upgraded, the connection is no longer HTTP. Framed WebSocket messages flow in both directions independently. Each frame has a 2-14 byte header containing an opcode (text, binary, ping, pong, close), payload length, and masking key (client-to-server frames must be masked per RFC to prevent cache poisoning by proxies).
Ping/Pong Keep-Alive: Either side can send a ping frame; the other must respond with a pong. This keeps the connection alive through NAT timeouts and detects broken connections.
Close Handshake: Either side initiates closure with a close frame containing an optional status code and reason. The other side echoes the close frame, and both sides close the TCP connection.
Compare with SSE for server-to-client-only streams that work over standard HTTP/2.