50·异步编程进阶

异步 IO 与文件操作

异步 IO 与文件操作

学习目标

  1. 掌握异步文件读写
  2. 掌握异步 TCP/UDP
  3. 理解缓冲 IO

核心概念

异步文件

use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 写文件
    let mut file = File::create("output.txt").await?;
    file.write_all(b"Hello, async!").await?;

    // 读文件
    let mut file = File::open("output.txt").await?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).await?;
    println!("{}", contents);

    Ok(())
}

异步 TCP

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

async fn handle_client(mut stream: TcpStream) {
    let mut buf = [0; 1024];
    let n = stream.read(&mut buf).await.unwrap();
    stream.write_all(&buf[..n]).await.unwrap();
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;
    loop {
        let (stream, _) = listener.accept().await?;
        tokio::spawn(handle_client(stream));
    }
}

缓冲 IO

use tokio::io::{BufReader, AsyncBufReadExt};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let file = tokio::fs::File::open("data.txt").await?;
    let reader = BufReader::new(file);
    let mut lines = reader.lines();

    while let Some(line) = lines.next_line().await? {
        println!("{}", line);
    }

    Ok(())
}

小结

操作API
创建文件File::create().await
打开文件File::open().await
读取read_to_string().await
写入write_all().await
TCP 监听TcpListener::bind().await
缓冲读取BufReader

练习编辑器

rust
Loading...