Card 03/ 10
Server-Sent Events on the Wire
A server sends events down one long HTTP response, and the browser reconnects and resumes on its own.
Server-sent events (SSE) deliver a stream of updates from server to browser inside one HTTP response that never finishes. The server writes each event as a few lines of text followed by an empty line. If the connection drops, the browser reconnects by itself and tells the server the last event it received, so the stream resumes where it stopped.
A browser starts one with new EventSource("/scores"). Below is part of the stream it receives. The stream is illustrative.
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
id: 40
event: goal
data: {"team":"home","score":"1-0"}
id: 41
data: {"minute":52}
: keep-aliveHow it starts. An ordinary GET with Accept: text/event-stream. The server answers with that content type and keeps the response open. No upgrade, no new protocol: any server or proxy that handles HTTP can carry it, as long as it does not hold the response back in a buffer.
Who may send. Only the server. The browser sends anything it needs to say, a chat message or a vote, as separate ordinary HTTP requests.
One message on the wire. Each event is lines of field: value, ended by an empty line. data carries the content, and several data lines join into one message. event names a type the page can listen for. id labels the event. A line starting with a colon is a comment, which servers send as a heartbeat to keep a quiet connection open. Events are UTF-8 text only.
After a drop. The browser waits a few seconds, or what the server set with a retry field, and sends the GET again with a Last-Event-ID header holding the last id it saw. If the stream above broke after event 41, the new request carries Last-Event-ID: 41, and a server that keeps recent events sends from 42 on.
One limit catches people out. Over HTTP/1.1, browsers allow about six connections per site, and each open stream holds one, so a seventh tab stalls. Over HTTP/2, all the streams share one connection and the limit disappears.
So when updates only flow one way, SSE gives most of what a WebSocket does, with recovery built in and nothing but HTTP underneath.
← → move through sections and cards