Skip to content

Instantly share code, notes, and snippets.

@acro5piano
Created April 11, 2024 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acro5piano/8e4ba1a7248e79f1362a3e18b482e9c2 to your computer and use it in GitHub Desktop.
Save acro5piano/8e4ba1a7248e79f1362a3e18b482e9c2 to your computer and use it in GitHub Desktop.
rust server sent event (EventSource) client with infinite reconnect loop
use anyhow::Result;
use eventsource_client::{Client, ReconnectOptions, SSE};
use futures::TryStreamExt;
use std::time::Duration;
const URL: &str = "http://localhost:8000/sse";
#[tokio::main]
async fn main() -> Result<()> {
let client = eventsource_client::ClientBuilder::for_url(URL)?
.header("Authorization", "Basic username:password")?
.reconnect(
ReconnectOptions::reconnect(true)
.retry_initial(false)
.delay(Duration::from_secs(1))
.backoff_factor(2)
.delay_max(Duration::from_secs(60))
.build(),
)
.build();
loop {
let mut stream = Box::pin(client.stream())
.map_ok(|event| match event {
SSE::Comment(comment) => println!("got a comment event: {:?}", comment),
SSE::Event(evt) => println!("got an event: {}", evt.data),
})
.map_err(|e| println!("error streaming events: {:?}", e));
while let Ok(Some(_)) = stream.try_next().await {}
tokio::time::sleep(Duration::from_secs(3)).await; // Add delay before reconnect
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment