Created
April 11, 2024 10:03
-
-
Save acro5piano/8e4ba1a7248e79f1362a3e18b482e9c2 to your computer and use it in GitHub Desktop.
rust server sent event (EventSource) client with infinite reconnect loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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