[][src]Function warp::filters::sse::keep_alive

pub fn keep_alive() -> KeepAlive

Keeps event source connection alive when no events sent over a some time.

Some proxy servers may drop HTTP connection after a some timeout of inactivity. This function helps to prevent such behavior by sending comment events every keep_interval of inactivity.

By default the comment is : (an empty comment) and the time interval between events is 15 seconds. Both may be customized using the builder pattern as shown below.

extern crate pretty_env_logger;
extern crate tokio;
extern crate warp;
use std::time::Duration;
use tokio::{clock::now, timer::Interval};
use warp::{Filter, Stream};

fn main() {
    let routes = warp::path("ticks")
        .and(warp::sse())
        .map(|sse: warp::sse::Sse| {
            let mut counter: u64 = 0;
            let event_stream = Interval::new(now(), Duration::from_secs(15)).map(move |_| {
                counter += 1;
                // create server-sent event
                warp::sse::data(counter)
            });
            // reply using server-sent events
            let stream = warp::sse::keep_alive()
                .interval(Duration::from_secs(5))
                .text("thump".to_string())
                .stream(event_stream);
            sse.reply(stream)
        });
}

See notes.