Card 01/ 10

ConceptDifficulty: Beginner2 min

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.

The three real-time protocols against the four questions this topic asks of each
QuestionWebSocketServer-sent eventsWebRTC
How it startsAn HTTP request that upgrades the connectionAn ordinary HTTP GET that never finishesAn offer and answer swapped through a server you choose
Who may sendBoth sides, at any timeOnly the serverBoth peers, directly to each other
One message on the wireA small binary frame on TCPLines of text in a long HTTP responseEncrypted packets on UDP
After a dropThe application must reconnectThe browser reconnects and resumes by itselfThe 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.