gpt4 book ai didi

rust - 为什么编译器说该参数未实现必需的特征?

转载 作者:行者123 更新时间:2023-12-03 11:42:30 24 4
gpt4 key购买 nike

我开始学习Rust语言已有一段时间,现在我正在为个人项目实现websocket服务器。如此说来,我不是专业的Rust程序员,我仍然处于学习基础的阶段。
我使用三个库tokiohypertokio-tungstenite开发该项目。我的HTTP服务器是用hyper编写的。基本上只有一个处理程序。该处理程序做一件事,将传入的UPGRADE HTTP请求升级为WebSocket连接。

use std::str;

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::prelude::*;

use hyper::header::{HeaderValue, UPGRADE, SEC_WEBSOCKET_ACCEPT};
use hyper::service::{make_service_fn, service_fn};
use hyper::upgrade::Upgraded;
use hyper::{Body, Client, Request, Response, Server, StatusCode};
use std::net::SocketAddr;

// A simple type alias so as to DRY.
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

async fn server_upgrade(req: Request<Body>) -> Result<Response<Body>> {
let mut res = Response::new(Body::empty());

// Send a 400 to any request that doesn't have
// an `Upgrade` header.
if !req.headers().contains_key(UPGRADE) {
*res.status_mut() = StatusCode::BAD_REQUEST;
return Ok(res);
}

// Setup a future that will eventually receive the upgraded
// connection and talk a new protocol, and spawn the future
// into the runtime.
//
// Note: This can't possibly be fulfilled until the 101 response
// is returned below, so it's better to spawn this future instead
// waiting for it to complete to then return a response.
let upgraded: Upgraded = match req.into_body().on_upgrade().await {
Ok(upgraded) => upgraded,
Err(e) => {
eprintln!("upgrade error: {}", e);
return Err(Box::new(e));
},
};
tokio_tungstenite::accept_async(upgraded);
Ok(res)
}
在第三行的最后,编译器发出一条错误消息,内容如下:
the trait bound `hyper::upgrade::Upgraded: tokio::io::async_read::AsyncRead` is not satisfied
the trait `tokio::io::async_read::AsyncRead` is not implemented for `hyper::upgrade::Upgraded`

the trait bound `hyper::upgrade::Upgraded: tokio::io::async_write::AsyncWrite` is not satisfied
the trait `tokio::io::async_write::AsyncWrite` is not implemented for `hyper::upgrade::Upgraded`
但是,当我查看 hyper::upgrade::Upgraded的文档时,我可以看到它实际上实现了那些特征。当我也查看 tokio-tunsgstenite的文档时,确实这些特征是来自同一 crate 的相同特征。
经验丰富的经验可以帮助我如何解决此问题,并使编译器确信 upgraded实例实现相同的特征吗?也许箱子之间的版本不匹配?
我还在这里附加我的 Cargo.toml文件。
[package]
name = "async-rs"
version = "0.1.0"
authors = ["Bora Semiz <Bora Semiz's email address>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
hyper = "0.13.9"
tokio = { version = "^0.2", features = ["full"] }
tokio-tungstenite = "0.12.0"

最佳答案

Hyper使用的是Tokio版本的0.2.x,而tokio-tungstenite使用的是Tokio版本的0.3.x。从Tokio 0.20.3的更改日志包括对AsyncReadAsyncWrite特征的重大更改,使这两个版本与它们的0.2版本不兼容。
您可以使用tokio_compat_02 crate 将两者桥接起来,直到Hyper发布新版本(还可以将自己的tokio版本升级为0.3中的Cargo.toml),或者将tokio-钨丝钨矿降级为0.11.0,如果愿意,可以使用tokio 0.2.x

关于rust - 为什么编译器说该参数未实现必需的特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65041342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com