Skip to main content

Module sse

Module sse 

Source
Expand description

Server-Sent Events (SSE).

Sse::stream answers with a text/event-stream response at once and returns an SseSender: events sent through it reach the client as they are sent — AI token output, progress, live updates — over HTTP/1.1, HTTP/2 and HTTP/3 alike. The stream ends when every sender is dropped; a client that went away shows up as SseClosed on the next send (a keep-alive comment every 15 seconds finds it even when nothing is sent).

Sse instead assembles a complete, buffered body from a known sequence of SseEvents.

§Wire format

Each event is a block of field: value\n lines terminated by a blank line:

id: 1
event: update
data: {"count":42}

Lines with no field name (starting with :) are comments and are ignored by clients; they are used here as keep-alive pings.

§Streaming

use rust_web_server::app::App;
use rust_web_server::sse::{Sse, SseEvent};

let app = App::with_state(()).get("/ticks", |_req, _params, _conn, _state| {
    let (events, response) = Sse::stream();
    std::thread::spawn(move || {
        for n in 1.. {
            let event = SseEvent::data(n.to_string()).id(n.to_string());
            if events.send(event).is_err() {
                break; // the client went away
            }
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    });
    response
});

§Buffered

use rust_web_server::sse::{Sse, SseEvent};

let response = Sse::new()
    .event("connected", "ready")
    .push(SseEvent::data(r#"{"count":1}"#).id("1").event_type("update"))
    .push(SseEvent::data(r#"{"count":2}"#).id("2").event_type("update"))
    .comment("keep-alive")
    .into_response();

Structs§

Sse
Builder for a buffered Server-Sent Events response.
SseClosed
The client is gone (or the response was never sent): stop sending.
SseEvent
A single Server-Sent Event.
SseSender
Sends events to one streaming SSE response; clone it to send from several places. The stream ends when the last clone is dropped.
SseStream
Options for a streaming SSE response; Sse::stream uses the defaults.