异步 IO 与文件操作
学习目标
- 掌握异步文件读写
- 掌握异步 TCP/UDP
- 理解缓冲 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 |