How a WebSocket Connection Begins
A WebSocket connection does not start as its own protocol on the wire; it begins life as an ordinary HTTP/1.1 GET request that asks the server to switch protocols. The client sends headers such as Connection: Upgrade and Upgrade: websocket, and if the server agrees, the same TCP socket that carried the HTTP request is repurposed into a persistent, full-duplex channel where either side can send frames at any time, without the request-response ping-pong that HTTP normally requires.
Cricket analogy: It's like a rain-affected ODI where umpires and captains agree mid-match to switch from a 50-over format to a Super Over decider on the same pitch, using the same players, rather than abandoning the game and starting a fresh fixture.
The Upgrade Handshake in Detail
The handshake is cryptographically verified so a server cannot be tricked by a plain HTTP request that merely looks like a WebSocket request. The client generates a random 16-byte value, base64-encodes it into the Sec-WebSocket-Key header, and the server must concatenate that key with the fixed GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, take the SHA-1 hash, base64-encode the result, and return it as Sec-WebSocket-Accept alongside an HTTP 101 Switching Protocols status line. If the client's computed expected value doesn't match what the server returned, the client must abort the connection.
Cricket analogy: It's like the DRS process where a batter's review isn't just taken on faith — the third umpire runs Hawk-Eye and UltraEdge against the original decision and only overturns it if the computed evidence matches the challenge, otherwise the review fails.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Closing a Connection Gracefully
WebSockets close with their own handshake layered on top of TCP's shutdown. Either endpoint sends a close frame (opcode 0x8) that optionally carries a numeric status code and a short UTF-8 reason string. The peer that receives it must send its own close frame back if it hasn't already initiated closing, and only after this exchange should the underlying TCP connection be torn down with a normal FIN sequence. Skipping this handshake, for example by killing the process or dropping the network abruptly, produces an abnormal closure that the other side sees as code 1006, which is never sent on the wire itself.
Cricket analogy: It's like the proper end-of-innings protocol where the umpire removes the bails and both captains shake hands to formally close play, versus a match abandoned mid-over due to bad light where no formal handshake ever happens.
Never assume a connection is closed just because you stopped receiving messages. Always listen for the close event (browser) or the close frame/callback (server library) and check the code and reason before cleaning up state — an idle connection and a genuinely closed one look identical until the close handshake or a timeout confirms it.
- A WebSocket connection begins as an HTTP request with Upgrade: websocket and Connection: Upgrade headers.
- The server proves it understood the request by hashing the client's Sec-WebSocket-Key with a fixed GUID and returning Sec-WebSocket-Accept.
- A successful handshake response is HTTP 101 Switching Protocols, after which the same TCP socket carries WebSocket frames instead of HTTP.
- Closing uses a dedicated close frame (opcode 0x8) exchanged by both peers before the TCP connection is torn down.
- Close frames can carry a numeric status code and a UTF-8 reason string explaining why the connection ended.
- Code 1006 signals an abnormal closure and is never actually transmitted — it only appears locally when the closing handshake never happened.
- Client libraries like the browser WebSocket object move through readyState values CONNECTING, OPEN, CLOSING, and CLOSED as the handshake and closure progress.
Practice what you learned
1. What HTTP status code indicates a successful WebSocket handshake?
2. What does the server do with the client's Sec-WebSocket-Key to produce Sec-WebSocket-Accept?
3. What opcode is used for a WebSocket close frame?
4. What does close code 1006 signify?
5. In the browser WebSocket API, which readyState value indicates the handshake is still in progress?
Was this page helpful?
You May Also Like
Text and Binary Frames
How WebSocket messages are broken into frames, and the difference between UTF-8 text frames and raw binary frames.
Ping/Pong and Heartbeats
How WebSocket ping and pong control frames keep connections alive and let both sides detect dead peers.
Close Codes and Error Handling
What WebSocket close codes mean, how to choose the right one, and how to build robust reconnect and error-handling logic around them.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics
Web DevelopmentNext.js Study Notes
JavaScript · 30 topics