tokio
tokio là một asynchronous runtime, giúp viết ứng dụng async trong Rust.
Cài đặt
cargo add tokio --features full
Hoặc
# File: Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }
Ví dụ
#[tokio::main]
async fn main() {
// This is running on a core thread.
let blocking_task = tokio::task::spawn_blocking(|| {
// This is running on a blocking thread.
// Blocking here is ok.
});
// We can wait for the blocking task like this:
// If the blocking task panics, the unwrap below will propagate the
// panic.
blocking_task.await.unwrap();
}
Ví dụ: Socket server
Ví dụ sau lấy từ document của tokio, một server đơn giản nhận kết nối từ client và trả về một thông báo.
use tokio::net::{TcpListener, TcpStream};
use mini_redis::{Connection, Frame};
#[tokio::main]
async fn main() {
// Bind the listener to the address
let listener = TcpListener::bind("127.0.0.1:6379").await.unwrap();
loop {
// The second item contains the IP and port of the new connection.
let (socket, _) = listener.accept().await.unwrap();
process(socket).await;
}
}
async fn process(socket: TcpStream) {
// The `Connection` lets us read/write redis **frames** instead of
// byte streams. The `Connection` type is defined by mini-redis.
let mut connection = Connection::new(socket);
if let Some(frame) = connection.read_frame().await.unwrap() {
println!("GOT: {:?}", frame);
// Respond with an error
let response = Frame::Error("unimplemented".to_string());
connection.write_frame(&response).await.unwrap();
}
}
Trên terminal:
cargo run
Trên một terminal khác:
(printf "PING\r\n";) | nc localhost 6379