How WebSockets differ from polling
A WebSocket is one connection between a client and a server that stays open and carries messages in both directions. The idea to keep: with polling the client has to ask every time, and with a WebSocket either side can speak once the connection is open.
The short version
With polling, the client keeps asking the server whether there is something new, and the server answers with an empty reply when there is not. Long polling makes the server hold each request until it has something to say, but every message is still a full HTTP request and response. A WebSocket starts as one HTTP request. After that the same TCP connection stays open, and both sides send small frames whenever they like.
Step by step
- The client sends an HTTP GET request with an
Upgrade: websocketheader. - The server answers
101 Switching Protocols. Any other status means the handshake did not complete. - The TCP connection stays open.
- Either side sends messages, each made of one or more frames, whenever it wants.
- Either side can end the connection with a Close frame.
| Short polling | Long polling | WebSocket | |
|---|---|---|---|
| Who starts an exchange | the client | the client | either side, after the handshake |
| Empty replies | yes, when nothing is new | no, the server waits for an event or a timeout | no requests to answer |
| Headers on every message | full HTTP headers | full HTTP headers | small frame fields |
Why it matters
Polling is simple but most questions can come back empty, while a WebSocket pushes data at once, and MDN notes that its API has no backpressure, so messages that arrive faster than the app can handle them can fill memory.
Sources
- RFC 6202: Known Issues and Best Practices for the Use of Long Polling and Streaming in Bidirectional HTTP — short and long polling, empty replies, full headers on every message
- RFC 6455: The WebSocket Protocol — the upgrade handshake, the 101 response, one TCP connection, frames, the Close frame
- MDN: The WebSocket API — two-way sessions without polling, and the lack of backpressure