Card 01/ 10
Beyond Request and Response: Three Real-Time Protocols
When the server has news, the client should not have to keep asking, and three protocols avoid that.
WebSocket, server-sent events (SSE) and WebRTC are three ways to keep a connection open so data can arrive the moment it exists, instead of when the client next asks. They differ in four things: how the connection starts, who may send on it, what one message looks like on the wire, and what happens when it drops. Those four questions are how each one is described in this topic.
Without them, a page that wants live updates polls: it asks the server every few seconds whether anything changed. Most answers are "no", each costs a full request with its headers, and news waits until the next poll.
| Question | WebSocket | Server-sent events | WebRTC |
|---|---|---|---|
| How it starts | An HTTP request that upgrades the connection | An ordinary HTTP GET that never finishes | An offer and answer swapped through a server you choose |
| Who may send | Both sides, at any time | Only the server | Both peers, directly to each other |
| One message on the wire | A small binary frame on TCP | Lines of text in a long HTTP response | Encrypted packets on UDP |
| After a drop | The application must reconnect | The browser reconnects and resumes by itself | The peers restart ICE to find a new path |
Each answer points at a use.
WebSocket turns one HTTP connection into a two-way channel of messages. It suits chat, multiplayer games, collaborative editing and anything where the client talks as often as the server.
Server-sent events keep one HTTP response open and write events into it as they happen. Only the server speaks, which suits notifications, live feeds and progress updates. The client still sends anything it has to say as normal HTTP requests.
WebRTC connects two browsers directly, without a server in the middle of the conversation, and carries audio, video and data with low delay. It suits calls and screen sharing, and costs the most to set up, because two machines behind home routers have to find each other first.
A useful first question is who needs to send. If only the server does, SSE is the simplest choice. If both do, WebSocket. If the data should go from one user's device to another's without a server relaying it, WebRTC.
So the three protocols are not rivals for one job: each removes polling for a different shape of conversation.
← → move through sections and cards