如何在 Rust 中的未来和流之间进行选择? [英] How to select between a future and stream in Rust?

查看:28
本文介绍了如何在 Rust 中的未来和流之间进行选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在 Rust 中试验 futures/tokio.我可以仅使用期货或仅使用流来做非常基本的事情.我想知道如何在未来和流之间进行选择.

I've just started experimenting with futures/tokio in Rust. I can do really basic things with just futures or just with streams. I was wondering how you can select between future and a stream.

如何将 tokio 文档中的玩具问题扩展为使用 tokio_timer::Timer 做一个定时的 HTTPS 请求?

How can I extend the toy problem from the tokio documentation to use tokio_timer::Timer to do a timed HTTPS request?

extern crate futures; // v0.1 (old)
extern crate native_tls;
extern crate tokio_core;
extern crate tokio_io;
extern crate tokio_tls;

use std::io;
use std::net::ToSocketAddrs;

use futures::Future;
use native_tls::TlsConnector;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Core;
use tokio_tls::TlsConnectorExt;

fn main() {
    let mut core = Core::new().unwrap();
    let handle = core.handle();
    let addr = "www.rust-lang.org:443".to_socket_addrs().unwrap().next().unwrap();

    let cx = TlsConnector::builder().unwrap().build().unwrap();
    let socket = TcpStream::connect(&addr, &handle);

    let tls_handshake = socket.and_then(|socket| {
        let tls = cx.connect_async("www.rust-lang.org", socket);
        tls.map_err(|e| {
            io::Error::new(io::ErrorKind::Other, e)
        })
    });
    let request = tls_handshake.and_then(|socket| {
        tokio_io::io::write_all(socket, "
            GET / HTTP/1.0

            Host: www.rust-lang.org

            

        ".as_bytes())
    });
    let response = request.and_then(|(socket, _request)| {
        tokio_io::io::read_to_end(socket, Vec::new())
    });

    let (_socket, data) = core.run(response).unwrap();
    println!("{}", String::from_utf8_lossy(&data));
}

推荐答案

您可以使用 FutureExt::into_stream 然后选择两个流:

You can convert a Future into a Stream using FutureExt::into_stream and then select on the two streams:

use futures::prelude::*; // 0.3.1

fn select_stream_or_future_as_stream<S, F>(stream: S, future: F) -> impl Stream<Item = S::Item>
where
    S: Stream,
    F: Future<Output = S::Item>,
{
    stream::select(future.into_stream(), stream)
}

另见:

这篇关于如何在 Rust 中的未来和流之间进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆