WebSockets: Under the Hood

July 24, 2025 1 min read 0 views

HTTP is stateless. WebSockets are stateful. How does the handshake work?

The Upgrade

It starts as a normal HTTP GET request.

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

If the server agrees, it responds:

Code
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade

Now, the TCP connection stays open. You don't send headers anymore. You send frames of binary data.

Heartbeats

Since the connection stays open, how do you know if the user is still there? Ping/Pong frames. The server sends a Ping. The client MUST send a Pong. If not, the connection is dead.

Conclusion

Real-time is not magic. It's just a raw TCP pipe that started life as an HTTP request.

Similar Posts