Available on crate feature sse only.
Expand description

Server-Sent Events (SSE)

Example

use std::time::Duration;
use std::convert::Infallible;
use futures_util::stream::iter;
use futures_util::Stream;

use salvo_core::prelude::*;
use salvo_extra::sse::{self, SseEvent};

fn sse_events() -> impl Stream<Item = Result<SseEvent, Infallible>> {
    iter(vec![
        Ok(SseEvent::default().data("unnamed event")),
        Ok(
            SseEvent::default().name("chat")
            .data("chat message")
        ),
        Ok(
            SseEvent::default().id(13.to_string())
            .name("chat")
            .data("other chat message\nwith next line")
            .retry(Duration::from_millis(5000))
        )
    ])
}
#[handler]
async fn handle(res: &mut Response) {
    sse::streaming(res, sse_events());
}
#[tokio::main]
async fn main() {
    let router = Router::with_path("push-notifications").get(handle);
    Server::new(TcpListener::bind("127.0.0.1:7878")).serve(router).await;
}

Each field already is event which can be sent to client. The events with multiple fields can be created by combining fields using tuples.

See also the EventSource API, which specifies the expected behavior of Server Sent Events.

Structs

SseError
Server-sent event
SseKeepAlive

Functions

Streaming