Script Valley
WebSockets & Real-Time Applications
How WebSockets Actually WorkLesson 1.2

The WebSocket handshake explained step by step

HTTP Upgrade header, Sec-WebSocket-Key, Sec-WebSocket-Accept, 101 Switching Protocols, connection lifecycle, handshake failure codes

From HTTP to WebSocket in One Handshake

A WebSocket connection starts as a plain HTTP/1.1 GET request with specific upgrade headers:

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

The server validates the request and responds with HTTP 101:

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

After this, the TCP connection stays open and switches to the WebSocket framing protocol. HTTP is no longer involved.

How Sec-WebSocket-Accept Is Computed

The server concatenates the client's Sec-WebSocket-Key with the magic string 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, SHA-1 hashes it, and Base64-encodes the result. This prevents HTTP caches from accidentally treating upgrade requests as normal responses. If the value does not match, the browser rejects the connection before any application code runs.

Common failure: a 403 means an origin check failed. A 404 means the server has no handler at that path. A 400 means required upgrade headers are missing.

Up next

WebSocket frames and message types

Sign in to track progress