[RUST]tokio异步使用的例子: 简单的标准输入输出服务

  • 功能:从标准输入stdin获取输入,并原样输出到标准输出stdout;
  • 关联:tokio crate的async、await、spawn、spawn_blocking等功能使用;
  • 依赖:
    Rust 版本:1.39.0 stable
    tokio: 0.2.4

Cargo.toml

[dependencies]
tokio = { version = "*", features = ["full"] }
  • 代码: main.rs
use std::io;
use tokio::{task, sync::mpsc};

#[tokio::main]
async fn main() {
    // producer
    let (mut tx_in, mut rx_in) = mpsc::channel::(800000);
    task::spawn(async move {
        loop {
            let mut line = String::new();
            line = task::spawn_blocking(move || {
                io::stdin().read_line(&mut line).unwrap();
                line
            }).await.unwrap();

            tx_in.send(line.trim().to_string()).await.unwrap();
        }
    });

    // reporter
    let (mut tx_out, mut rx_out) = mpsc::channel::(800000);
    task::spawn(async move {
        loop {
            match rx_out.recv().await {
                Some(data) => {
                    task::spawn_blocking(move || {
                        println!("{}", data);
                    }).await.unwrap();
                }, 

                None => ()
            }
        }
    });

    // worker
    loop {
        match rx_in.recv().await {
            Some(data) => {
                tx_out.send(data).await.unwrap();
            }, 

            None => ()
        }
    }
}

你可能感兴趣的:(RUST)