Skip to main content

Module sse

Module sse 

Source
Expand description

Server-Sent Events

use ullun::prelude::*;
use ullun::sse::{sse, Event};

async fn ticker(_req: Request) -> Result<Response> {
    let (tx, res) = sse();
    tokio::spawn(async move {
        for n in 1..=3 {
            let event = Event::data(format!("tick {n}")).event("tick").id(n.to_string());
            if tx.send(event).await.is_err() {
                return; // browser closed the tab
            }
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
        }
    });
    Ok(res)
}

Browser side: new EventSource("/ticker").addEventListener("tick", e => ...). Newlines in field values cannot inject extra fields: event and id have them removed, data is split into one data: line per line.

Structs§

Event
One server-sent event
SseSender
Sends events of an SSE response

Functions§

sse
An SSE response with the right headers (text/event-stream, no caching, no proxy buffering) and the sender for its events