rust - 从 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
的缓冲区中读取。
解决方案
正如您的错误消息所述,有一个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]);
推荐阅读
- git - 如何将 git 重置回我推送的内容
- node.js - GitLab CI 错误作业失败(系统故障)
- javascript - 如何验证或检查提示值是否在对象中
- pytorch - Pytorch autograd:使参数的梯度成为另一个参数的函数
- xero-api - XERO PHP SDK createPayment 验证异常
- r - 将数据与R中的重复行合并
- web-services - postman:“MasterDataReplReqMsg”元素上的命名空间,不是有效的 SOAP 版本
- javascript - 带有 getElementsByClassName("") 的切换器不起作用
- github - 有没有办法在 Github 上轻松搜索/列出模板存储库?
- r - R聚合尚未定义的列范围(包括因子)