异步支持库
tokio
老牌集装箱
[dependencies]
# An event-driven, non-blocking I/O platform for writing asynchronous I/O backed applications.
tokio = { version = "1.5.0", features = ["full"] }
async_std
语法更接近现代Rust
以同步的思维编写异步逻辑
async fn tcp_serv() -> ! {
let listener = tokio::net::TcpListener::bind("0.0.0.0:2222").await.unwrap();
loop {
println!("wait a conn...");
let (stream, addr) = listener.accept().await.unwrap();
let task = async move {
println!("user {} connected.", addr);
let intro_time = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap();
tokio::time::sleep(std::time::Duration::from_millis(8000)).await;
let end_time = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap();
let time = end_time - intro_time;
let id = std::thread::current().id();
stream.try_write(format!("id: {:?}, time: {:?}", id, time).to_string().as_bytes()).unwrap();
println!("{} done.", addr);
};
tokio::spawn(task);
}
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
tcp_serv().await;
println!("Done.");
Ok(())
}
异步有什么用
https://fasterthanli.me/articles/pin-and-suffering