https://without.boats/blog/why-async-rust/
Rust future中的三个概念:
An executor decides when and how to execute your futures.
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
// TODO
}
// 目前还不支持async的迭代器
for stream in listener.incoming() {}
fn main() -> Result<(), Box<dyn Error>> {
let (_, bp) = backpressure::new(10);
task::block_on(async {
let listener = TcpListener::bind("localhost:8080").await?;
eprintln!("Accepting connections on localhost:8080");
let mut incoming = listener.incoming()
.log_warnings(log_accept_error)
.handle_errors(Duration::from_millis(500))
.backpressure_wrapper(bp);
while let Some(stream) = incoming.next().await {
task::spawn(async {
if let Err(e) = connection_loop(stream).await {
eprintln!("Error: {}", e);
}
});
}
Ok(())
})
}
async fn connection_loop(mut stream: ByteStream) -> Result<(), io::Error> {
println!("Connected from {}", stream.peer_addr()?);
task::sleep(Duration::from_secs(5)).await;
stream.write_all("hello\\n".as_bytes()).await?;
Ok(())
}
fn log_accept_error(e: &io::Error) {
eprintln!("Accept error: {}. Sleeping 0.5s. {}", e, error_hint(&e));
}