Concepts / The web

The web

WebSocket

Also called WebSockets, wss, 101 Switching Protocols, Sec-WebSocket-Key, server-sent events, long polling

One connection kept open after an HTTP upgrade, where either side can send a message at any moment.

One HTTP request, then a line open both ways
One HTTP request, then a line open both ways

A WebSocket starts as one ordinary HTTP request asking to upgrade. After 101 Switching Protocols, HTTP is over and the same TCP connection carries frames, which either side sends the moment it has something to say, without being asked. Between frames nothing crosses at all, and a proxy that doesn't pass the upgrade on stops the whole thing before it starts.

A client sends an ordinary HTTP request with Upgrade: websocket and Connection: Upgrade, and the server answers 101 Switching Protocols. From then on the connection carries frames: a small header (2 to 14 bytes) and the data. Frames from a client are masked with four random bytes, to keep proxies from misreading them, not for secrecy; wss:// adds TLS for that. Upgrade and Connection are hop by hop, so every proxy has to pass them on by choice. Quiet connections get closed, so ping and pong frames keep them alive. For data that only flows from server to client, server-sent events do the job over plain HTTP.

See it on real machines

Read next

Learn it on real machines.

Every lab is a small network of real Linux machines in your browser. Sign in with Google or email to start.

Start this lab