use std::time::Duration;
use netring::monitor::Monitor;
use netring::protocol::builtin::Http;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let iface = std::env::args().nth(1).unwrap_or_else(|| "lo".into());
let monitor = Monitor::builder()
.interface(&iface)
.with_broadcast::<Http>()
.name("stream-consumer-demo")
.build()?;
let mut http_stream = monitor.subscribe::<Http>()?;
eprintln!(
"[stream-consumer] watching {iface} for 60s; \
HTTP messages will print as `[stream] <msg>` from the consumer task"
);
let consumer = tokio::spawn(async move {
let mut buf = Vec::new();
let mut total = 0u64;
loop {
tokio::time::sleep(Duration::from_millis(100)).await;
let n = http_stream.recv_many(&mut buf, 32);
for msg in buf.drain(..) {
total += 1;
println!("[stream] http #{total}: {msg:?}");
}
if n == 0 && http_stream.subscribers() == 1 {
break;
}
}
eprintln!("[stream-consumer] consumer drained {total} messages");
});
monitor.run_for(Duration::from_secs(60)).await?;
let _ = tokio::time::timeout(Duration::from_secs(2), consumer).await;
Ok(())
}