Skip to main content

Module sse

Module sse 

Source
Expand description

Server-Sent Events: a response that stays open and delivers events as they happen.

Lighter than a WebSocket for the case it fits — the server talks, the browser listens — and the browser’s EventSource reconnects on its own, sending Last-Event-ID so a handler can resume where the client left off. Progress of a background job is the textbook case: one direction, a few events a second at most, and a client that must not miss the last one.

r.get("/jobs/{id}/events", |req: Request| async move {
    let (tx, rx) = sse::channel(16);
    tokio::spawn(async move {
        for step in 0..=100 {
            if tx.send(Event::json("progress", Json::object([("percent", step.into())]))).await.is_err() {
                break; // the client went away
            }
        }
    });
    Response::events(rx)
});

§What the wire looks like

One event is a few field: value lines and a blank line. data: may repeat, one line each — a newline inside the data would otherwise end the event early, so it is split for you. A comment line (: …) is sent every fifteen seconds while nothing else is: a proxy that sees no bytes for a minute closes the connection, and the client would then reconnect for no reason.

Structs§

Event
One event.

Constants§

KEEPALIVE
How often a comment is written to keep an idle connection open.

Functions§

channel
The sending half of an event stream, and the receiver Response::events takes. capacity is how many events may wait for a slow client before the sender is made to wait too.