asynchronous - 如何链接 tokio 阅读功能?

标签 asynchronous rust rust-tokio

有没有办法以“递归”方式链接 tokio::io 中的 read_* 函数?

我基本上是想做类似的事情:

read_until x 然后 read_exact y 然后写响应然后回到顶部。

如果您对我所说的功能感到困惑:https://docs.rs/tokio/0.1.11/tokio/io/index.html

最佳答案

是的,有办法。

read_until is 返回一个结构 ReadUntil , 它实现了 Future -trait,它本身提供了很多有用的功能,例如and_then可用于链接 future 。

一个简单(愚蠢)的例子如下所示:

extern crate futures;
extern crate tokio_io; // 0.1.8 // 0.1.24

use futures::future::Future;
use std::io::Cursor;
use tokio_io::io::{read_exact, read_until};

fn main() {
    let cursor = Cursor::new(b"abcdef\ngh");
    let mut buf = vec![0u8; 2];
    println!(
        "{:?}",
        String::from_utf8_lossy(
            read_until(cursor, b'\n', vec![])
                .and_then(|r| read_exact(r.0, &mut buf))
                .wait()
                .unwrap()
                .1
        )
    );
}

这里我使用了一个 Cursor,它恰好实现了 AsyncRead -trait 并使用 read_until 函数读取直到出现换行符(在 'f''g' 之间)。
然后链接那些我使用 and_then 以使用 read_exact 以防成功,使用 wait得到 Result 展开它(不要在生产 child 中这样做!)并从元组中获取第二个参数(第一个是游标)。
最后,我将 Vec 转换为字符串以使用 println! 显示 "gh"

关于asynchronous - 如何链接 tokio 阅读功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52887688/

相关文章:

rust - 东京 curl : capture output into a local `Vec` - may outlive borrowed value

postgresql - 当字段类型在编译时未知时,如何使用tokio-postgres枚举列?

rust - 如何从 tokio-proto 连接握手中检索信息?

jquery - 呈现时,该行已被另一个事务更新或删除

types - Rust 有 C 的 typedef 的等价物吗?

java - 如何针对特定场景正确使用Apache Camel?

rust - 当我想使用 Result 时,Match 期望 &Result

rust - 为什么这个 rust HashMap 宏不再起作用了?

wcf - 为什么我的消息在单个 WCF TCP channel (使用 ConcurrencyMode.Reentrant)上被乱序处理?

asynchronous - Inno Setup 中的异步 WMI 查询