在 Rust 中使用 `tokio-rustls` 从 TlsStream<TcpStream> 读取

Read from TlsStream<TcpStream> using `tokio-rustls` in Rust

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

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'

我正在寻找使用 tokio-rustls 生成的 TlsStream 来缓冲。

如您的错误消息所述,存在一个特征 AsyncReadExt that's implemented for the type, but not imported into scope. To be able to use the read method of that trait, you need to import the trait; for this trait, this is typically done by importing the tokio prelude:

use tokio::prelude::*;

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

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

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