有没有办法以“递归”方式链接 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/