Rust异步编程(1)-async和await

async和await

1. 为什么异步编程

使用少量线程,减少开销,达到高效异步。也就是async的使用
如下案例,一个线程,达到了多线程异步的效果

2. 原理

reactor通过通知executor,让executor选择性的执行任务(类似future)

3. 客户端

使用了关键词async

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::net::TcpStream;
use std::io::{ prelude::*, BufReader, Write };
use std::str;
use futures::join;
use futures::executor;

fn use_server(server: &str, port: u16, content: &str) -> std::io::Result<()> {
let mut stream = TcpStream::connect((server, port))?;
let _ = stream.write(content.as_bytes())?;
let mut reader = BufReader::new(&stream);
let mut buffer: Vec<u8> = Vec::new();
reader.read_until(b'\n', &mut buffer)?;
println!("recv from server: {} ", str::from_utf8(&buffer).unwrap());
Ok(())
}
async fn async_use_server(server: &str, port: u16, content: &str) {
use_server(server, port, content).unwrap();
}
async fn use_all_server() {
let f1 = async_use_server("127.0.0.1", 8080, "use server1 download 127.0.0.1:8080");
let f2 = async_use_server("127.0.0.1", 8081, "use server2 download 127.0.0.1:8081");
join!(f1, f2);
}
fn main() -> std::io::Result<()> {
let f = use_all_server();
executor::block_on(f);
Ok(())
}

4. 服务器端

总共需要启动两个服务器端,代码基本一样,只是端口号和wait_time不一样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::thread;
use std::time;

fn handle_client(mut stream: TcpStream, wait_time: u64) -> std::io::Result<()> {
let mut buf = [0; 512];
loop {
let bytes_read = stream.read(&mut buf)?;
if bytes_read == 0 {
return Ok(());
}
thread::sleep(time::Duration::from_secs(wait_time));
stream.write(&buf[..bytes_read])?;
stream.write(&("\n".as_bytes()))?;
}
}

fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:8080")?;

for stream in listener.incoming() {
handle_client(stream?, 3)?;
}

Ok(())
}

总结

本文编辑完毕

参考

[1] Rust 异步编程

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信