Plain HTTP works as “request and response”: the client asks, the server answers, and the server cannot send data on its own. For chats, games and live quotes this had to be worked around by polling the server and opening a separate connection for every message. WebSocket, defined in RFC 6455 (December 2011), solves the problem with one persistent channel.
How a connection is opened
It all starts with an ordinary HTTP GET request with the Upgrade and Connection headers: the client asks to switch protocols. The server replies with status 101 and a Sec-WebSocket-Accept value computed from Sec-WebSocket-Key, so that the client can be sure it is talking to a real WebSocket server. After that both sides use the same TCP connection directly, and HTTP no longer takes part in the exchange. The URL schemes are ws:// (port 80 by default) and wss:// (port 443, the same protocol inside TLS). In the browser, the WebSocket constructor, an interface from the WHATWG standard, handles the connection.
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Version: 13 HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Frames, ping and closing
Data travels in frames: text (opcode 0x1) or binary data (0x2); the protocol can split a large message into several frames. The control frames are close, ping and pong: either side may send a ping, and the other must reply with a pong carrying the same content as soon as possible, which is how liveness is checked. Closing is also polite: one side sends a close frame with a reason code, for example 1000 for a normal closure, and the other side acknowledges it.
| Frame | Opcode | Purpose |
|---|---|---|
| Text | 0x1 | a message encoded as UTF-8 |
| Binary | 0x2 | arbitrary bytes |
| Close | 0x8 | closes the connection with a reason code |
| Ping | 0x9 | checks that the connection is alive |
| Pong | 0xA | reply to a ping with the same content |
Where it is used
RFC 6455 names typical cases: games, stock tickers, collaborative editing, and real-time interfaces to services; in practice the list is longer and includes chats and messengers. Every open connection takes up server memory and file descriptors, so their number is limited. Passing WebSocket through a reverse proxy takes separate settings, because ordinary proxying is designed for “request and response”. If the server only needs to push events down to the client, a simpler mechanism is often enough: Server-Sent Events over plain HTTP.
Sources
the term is written from these pagesVerified 9 Nov