Function choices::warp::filters::sse::keep_alive [−][src]
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.
use std::time::Duration; use std::convert::Infallible; use futures::StreamExt; use tokio::time::interval; use tokio_stream::wrappers::IntervalStream; use warp::{Filter, Stream, sse::Event}; // create server-sent event fn sse_counter(counter: u64) -> Result<Event, Infallible> { Ok(Event::default().data(counter.to_string())) } fn main() { let routes = warp::path("ticks") .and(warp::get()) .map(|| { let mut counter: u64 = 0; let interval = interval(Duration::from_secs(15)); let stream = IntervalStream::new(interval); let event_stream = stream.map(move |_| { counter += 1; sse_counter(counter) }); // reply using server-sent events let stream = warp::sse::keep_alive() .interval(Duration::from_secs(5)) .text("thump".to_string()) .stream(event_stream); warp::sse::reply(stream) }); }
See notes.