我遵循the mdns Rust documentation并粘贴了示例代码,但它会引发以下错误:

thread 'main' panicked at 'there is no reactor running, must be called from the context of Tokio runtime'

以下是我的代码:

use futures_util::{pin_mut, stream::StreamExt};
use mdns::{Error, Record, RecordKind};
use std::{net::IpAddr, time::Duration};

const SERVICE_NAME: &'static str = "_googlecast._tcp.local";

#[tokio::main]
async fn main() -> Result<(), Error> {
    // Iterate through responses from each Cast device, asking for new devices every 15s
    let stream = mdns::discover::all(SERVICE_NAME, Duration::from_secs(15))?.listen();
    pin_mut!(stream);

    while let Some(Ok(response)) = stream.next().await {
        let addr = response.records().filter_map(self::to_ip_addr).next();

        if let Some(addr) = addr {
            println!("found cast device at {}", addr);
        } else {
            println!("cast device does not advertise address");
        }
    }

    Ok(())
}

fn to_ip_addr(record: &Record) -> Option<IpAddr> {
    match record.kind {
        RecordKind::A(addr) => Some(addr.into()),
        RecordKind::AAAA(addr) => Some(addr.into()),
        _ => None,
    }
}

依赖项:

[dependencies]
mdns = "1.1.0"
futures-util = "0.3.8"
tokio = { version = "0.3.3", features = ["full"] }

我错过了什么?我试着在网上查找,但还没有找到如何为这个用例创建一个react 堆.

推荐答案

您正在使用较新版本的Tokio,例如0.3或1.x、 许多软件包,包括mdns 1.1.0,都依赖于旧版本的Tokio,比如0.2.

% cargo tree -d
tokio v0.2.22
└── mdns v1.1.0
    └── example_project v0.1.0

tokio v0.3.3
└── example_project v0.1.0

目前,您需要匹配东京运行时的版本.最简单的方法是自己使用东京0.2.tokio-compat-02 crate 在某些情况下也可能有用.

另见:


具有相同根本原因的各种错误消息:

没有react 堆运行,必须从东京1号的上下文中调用.x运行时

没有react 堆运行,必须从东京运行时的上下文调用

目前没有在东京运行时运行

Rust相关问答推荐

把Vector3变成Vector4的绝妙方法

为什么复印是豆荚的一个重要特征?

如何使用 list 在Rust for Windows中编译?

当一个箱子有自己的依赖关系时,两个人如何克服S每箱1库+n箱的限制?

编译项目期间使用Cargo生成时出现rustc错误

如何使用盒装枚举进行模式匹配?

在铁 rust 中传递所有权

除了调用`waker.wake()`之外,我如何才能确保future 将再次被轮询?

我如何制作一个变异迭代器来锁定内部数据直到删除?

Rust编译器似乎被结果类型与anyhow混淆

如何在Rust中基于字符串 Select struct ?

当我try 使用 SKI 演算中的S I I实现递归时,为什么 Rust 会失败?

在 Rust 中,是否可以定义一个需要实现类型的构造函数的对象安全特征?

为什么这个闭包没有实现Fn?

为什么带有生命周期指定的方法不能被调用两次?

以 `static` 为前缀的闭包是什么意思?我什么时候使用它?

如何在 Rust Polars 中可靠地连接 LazyFrames

在 Rust 中获得准确时间的正确方法?

如何从 many0 传播 Nom 失败上下文?

如何在 Rust 中构建一个 str