任务

Rust 有一个任务系统,这是一种轻量级线程处理形式。

每个任务只有一个顶级 Future,执行器会对此进行轮询来推进任务进度。该 Future 可能包含一个或多个嵌套的 Future,可以通过其 poll 方法对它们进行轮询,类似于调用堆栈。可以通过轮询多个子 Future(例如争用定时器和 I/O 操作)在任务内部实现并发操作。

use tokio::io::{self, AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:0").await?;
    println!("listening on port {}", listener.local_addr()?.port());

    loop {
        let (mut socket, addr) = listener.accept().await?;

        println!("connection from {addr:?}");

        tokio::spawn(async move {
            socket.write_all(b"Who are you?\n").await.expect("socket error");

            let mut buf = vec![0; 1024];
            let name_size = socket.read(&mut buf).await.expect("socket error");
            let name = std::str::from_utf8(&buf[..name_size]).unwrap().trim();
            let reply = format!("Thanks for dialing in, {name}!\n");
            socket.write_all(reply.as_bytes()).await.expect("socket error");
        });
    }
}

将此示例复制到准备好的 src/main.rs 文件中,并从该文件运行它。

请尝试使用像 nctelnet 这样的 TCP 连接工具进行连接。

  • 让学生想象一下,当连接多个客户端时,示例服务器会达到怎样的状态。存在哪些任务?具有哪些 Future?

  • This is the first time we’ve seen an async block. This is similar to a closure, but does not take any arguments. Its return value is a Future, similar to an async fn.

  • Refactor the async block into a function, and improve the error handling using ?.