Card 02/ 10
The WebSocket Upgrade: From HTTP to a Two-Way Channel
A WebSocket starts as an ordinary HTTP request that asks to change protocol, and the server agrees with a 101.
A WebSocket begins as an HTTP/1.1 request asking the server to switch the connection to another protocol. If the server agrees, it replies 101 Switching Protocols, and from then on the same TCP connection carries WebSocket frames, small binary messages, in both directions. Nothing new is opened; the connection that carried the request becomes the channel.
Follow a browser opening a chat channel with new WebSocket("wss://chat.example.com/room"). The key values are the example ones from RFC 6455, the WebSocket specification.
Opening the channel, step by step
The client asks to upgrade
The browser opens a TCP connection, and TLS for wss://, then sends a GET with Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Version: 13 and Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==, a random value encoded as text.
The server agrees
The server replies HTTP/1.1 101 Switching Protocols with Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=. That value is computed from the client's key and a fixed string in the specification, which proves the server understood a WebSocket request rather than echoing an ordinary one.
Both sides send frames
The HTTP exchange is over. Either side may now send a frame at any time, without waiting for the other.
Who may send. Both sides, independently. A server can push a message the instant another user types one, and the browser can send while a message is arriving.
One message on the wire. A frame has a header of at least two bytes, saying whether it is the last piece of a message, what kind it is (text, binary, close, ping or pong) and how long it is, followed by the data. Frames sent from the browser are masked, mixed with four random bytes, which stops a badly behaved proxy from mistaking them for something it should cache.
After a drop. The protocol does not reconnect. When the TCP connection breaks, the browser fires a close event, and the application must open a new WebSocket, usually after a short, growing wait, and ask the server for whatever it missed.
So a WebSocket is an HTTP request that changes into a two-way stream of frames, and recovery is the application's job.
← → move through sections and cards