如果发生某些情况,完成未来

时间:2018-02-07 12:40:23

标签: asynchronous rust future rust-tokio

如果通过UDP连接收到某个值,我想创建一个完成的未来。

为了澄清,假设我发送一个id为2的ping,并希望异步等待具有相同id的pong。我的想法是使用类似send_ping(endpoint, id) -> Future的东西,并使用未来(例如将其传递给其他函数),因为它知道它要么解析为匹配的乒乓还是超时。

我的想法草图:

extern crate tokio_core;
extern crate futures;

use tokio_core::reactor::*;
use futures::Stream;
use futures::sync::mpsc;

fn main() {
    let mut core = Core::new().unwrap();

    // simulate my UDP socket connection
    let (remote, socket) = mpsc::unbounded::<i32>();
    remote.unbounded_send(1).unwrap();
    remote.unbounded_send(2).unwrap();
    remote.unbounded_send(3).unwrap();

    let reader = socket.for_each(|id| {
        println!("received {}", id);
        Ok(())
    });

    // create future which completes if 2 is received
    // or after a given timeout

    core.run(reader).unwrap();
}

这甚至可能吗?我找不到任何例子。

1 个答案:

答案 0 :(得分:0)

您可以使用tokio_timer::Timer::timeout_streamfutures::Stream::filter

extern crate futures;
extern crate tokio_core;
extern crate tokio_timer;

use tokio_core::reactor::*;
use futures::Stream;
use futures::sync::mpsc;
use std::time::Duration;

fn main() {
    let mut core = Core::new().unwrap();
    let timer = tokio_timer::Timer::default();

    // simulate my UDP socket connection
    let (remote, socket) = mpsc::unbounded::<i32>();
    remote.unbounded_send(1).unwrap();
    remote.unbounded_send(2).unwrap();
    remote.unbounded_send(3).unwrap();

    let consumer = timer
        .timeout_stream(socket, Duration::from_secs(2))
        .filter(|&v| v == 2)
        .for_each(|id| {
            println!("received {}", id);
            Ok(())
        });

    println!("{:?}", core.run(consumer));
}
相关问题