我正在尝试使用tokio和mqtt_v5机箱中提供的编解码器创建一个MQTT连接。我的代码不能编译,我不明白为什么。这是我到目前为止所写的代码,发送代码可能不正确。
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use tokio_util::codec::Decoder;
use std::net::SocketAddrV4;
use mqtt_v5::types::Packet as MqttPacket;
use mqtt_v5::codec::MqttCodec;
use futures_sink::Sink;
use futures_core::stream::Stream;
struct MqttConn {
inner: Framed<TcpStream, MqttCodec>,
}
impl MqttConn {
async fn new(addr: SocketAddrV4) -> MqttConn {
let tcp = TcpStream::connect(addr).await.expect("cannot connect to mqtt");
MqttConn { inner: MqttCodec::new().framed(tcp) }
}
async fn handle(&self, handler: &dyn Fn(&MqttConn, MqttPacket) -> ()) {
while let Some(p) = self.inner.next().await {
handler(self, p)
}
}
async fn send(&self, p: MqttPacket) {
self.inner.start_send(p);
}
}我从编译器得到以下错误:
error[E0599]: no method named `framed` found for struct `MqttCodec` in the current scope
--> src/mqtt.rs:17:44
|
17 | MqttConn { inner: MqttCodec::new().framed(tcp) }
| ^^^^^^ method not found in `MqttCodec`
|
= help: items from traits can only be used if the trait is in scope
= note: the following trait is implemented but not in scope; perhaps add a `use` for it:
`use tokio_util::codec::decoder::Decoder;`
error[E0599]: no method named `next` found for struct `Framed<tokio::net::TcpStream, MqttCodec>` in the current scope
--> src/mqtt.rs:21:40
|
21 | while let Some(p) = self.inner.next().await {
| ^^^^ method not found in `Framed<tokio::net::TcpStream, MqttCodec>`
error[E0599]: no method named `start_send` found for struct `Framed<tokio::net::TcpStream, MqttCodec>` in the current scope
--> src/mqtt.rs:27:20
|
27 | self.inner.start_send(p);
| ^^^^^^^^^^ method not found in `Framed<tokio::net::TcpStream, MqttCodec>`
warning: unused import: `tokio_util::codec::Decoder`
--> src/mqtt.rs:3:5
|
3 | use tokio_util::codec::Decoder;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: unused import: `futures_sink::Sink`
--> src/mqtt.rs:7:5
|
7 | use futures_sink::Sink;
| ^^^^^^^^^^^^^^^^^^编译器说Decoder特征不在作用域中,但我使用了它。如果我尝试建议的导入,我发现模块tokio_util::codec::decoder是私有的。基于源,tokio_util::codec::decoder::Decoder被重新导出为tokio_util::codec::Decoder。另外,如果我没看错文档,Framed应该实现Sink和Stream,因此它应该有next和start_send方法。
来自Cargo.toml的相关行:
[dependencies]
tokio = { version = "1.0.1", features = ["full"] }
tokio-util = { version = "0.6", features = ["full"] }
futures-sink = "0.3.9"
futures-core = "0.3.9"
mqtt-v5 = "0.1.1"我怎样才能编译这段代码?
发布于 2021-01-16 03:09:50
您有许多库不兼容问题,它们导致了一些不太明显的错误消息。
mqtt-v5 depends on tokio-util^0.3,它是为tokio 0.2而不是1.0编写的。您需要回滚到tokio 0.2和tokio-util 0.3。这应该可以解决Decoder和Sink的问题。
此外,Stream特征只提供poll_next(),这是任务级的流方法。next()是由StreamExt特性提供的,以及其他类似于Iterator中的便捷方法。
https://stackoverflow.com/questions/65734815
复制相似问题