Part 3 of 8 · 2 min read
Protocols
How the server reaches the client.
HTTP starts every exchange from the client. For the sender this is fine: the client sends the message, and a kept-alive connection avoids repeated handshakes. The receiver is harder, because the server has to push. The book lists three techniques.
Polling. The client asks every few seconds, "any new messages?" Most answers are "no", so the server spends effort on empty replies.
Long polling. The client asks and the server holds the request until a message arrives or a timeout passes. The client then asks again at once. It wastes less, but it has three flaws the book names. Sender and receiver may be on different servers, so the server that has the message may not hold the receiver's request. The server cannot tell well when a client has gone. And an idle user still reconnects after every timeout.
WebSocket. The client opens an ordinary HTTP connection and upgrades it. The result is a two-way, persistent channel. It works through most firewalls, because it uses the same ports as web traffic (80 and 443). Since it is two-way, it can serve both sending and receiving, which simplifies the design.
A worked example (made up). A user receives 1 message an hour. Polling every 5 seconds makes 720 requests an hour for 1 useful answer. A WebSocket keeps one connection and carries that one message.
Not everything needs WebSocket. Sign-up, login and profiles are ordinary request and response work, and use plain HTTP.
WebSocket
A WebSocket is a two-way channel that begins as an HTTP request and then stays open, so server and client can both send at any time.
Example: a chat server pushes a new message down the open channel the moment it arrives.
Check yourself: 1. Why is polling wasteful for a quiet user? 2. Name one flaw of long polling. 3. Which features of a chat app can stay on plain HTTP?