首页 > 解决方案 > 从 TlsStream 读取在 Rust 中使用 `tokio-rustls`

问题描述

我正在使用rustls,并且想像TlsStream我们读取一样读取到缓冲区TcpStream。这是我正在做的事情:

let acceptor = TlsAcceptor::from(Arc::new(config));

let fut = async {

    let mut listener = TcpListener::bind(&addr).await?;

    loop {

        let (stream, peer_addr) = listener.accept().await?;
        let acceptor = acceptor.clone();

        let fut = async move {

            let mut stream = acceptor.accept(stream).await?;

            //// CURRENTLY THIS .read() is throwing error in compiler
            println!("Stream: {:?}", stream.read(&mut [0; 1024]));

            Ok(()) as io::Result<()>
        };

        handle.spawn(fut.unwrap_or_else(|err| eprintln!("{:?}", err)));
    }
};

它抛出错误

'error[E0599]: no method named `read` found for struct `tokio_rustls::server::TlsStream<tokio::net::tcp::stream::TcpStream>` in the current scope'

我希望从TlsStream生成tokio-rustls的缓冲区中读取。

标签: rustrust-tokio

解决方案


正如您的错误消息所述,有一个AsyncReadExt为该类型实现的特征,但未导入范围。为了能够使用该read特征的方法,您需要导入该特征;对于这个特性,这通常是通过导入tokio prelude来完成的:

use tokio::prelude::*;

// or you can explicitly import just AsyncReadExt, but I'd recommend the above
use tokio::io::AsyncReadExt;

此外,您需要特别await指定 from 的结果read(),因为它返回一个未来。您还需要在单独的变量中使用缓冲区,因为这是存储读取数据的地方。

let mut buffer = [0; 1024];
let byte_count = stream.read(&mut buffer).await;
//                                       ^^^^^^
println!("Stream: {:?}", &buffer[0..byte_count]);

推荐阅读