【问题标题】:Why do I get the error "there is no reactor running, must be called from the context of Tokio runtime" even though I have #[tokio::main]?即使我有 #[tokio::main],为什么我会收到错误“没有反应器正在运行,必须从 Tokio 运行时的上下文中调用”?
【发布时间】:2020-11-11 03:08:09
【问题描述】:

我正在关注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"] }

我错过了什么?我尝试在网上查找,但没有找到如何为这个用例创建反应器。

【问题讨论】:

    标签: rust rust-tokio


    【解决方案1】:

    您使用的是较新版本的 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
    

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

    另见:


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

    没有正在运行的反应器,必须从 Tokio 1.x 运行时的上下文中调用

    没有反应器在运行,必须从 Tokio 运行时的上下文中调用

    当前未在 Tokio 运行时上运行

    【讨论】:

      【解决方案2】:

      对我的修复是将其添加到 Cargo.toml:

      [dependencies]
      async-std = { version = "1", features = ["attributes", "tokio1"] }
      

      https://github.com/ATiltedTree/ytextract/issues/25

      【讨论】:

        【解决方案3】:

        在撰写本文时,相当多的 crate 已经在使用 Tokio v1,但其他的可能仍处于试验阶段。检查您的板条箱中是否有可能已升级其 tokio 运行时兼容性的 预发布版本

        这方面的一个相关示例是actix-web,它从版本 4 开始使用 Tokio 的运行时 1.0,仍处于测试阶段。

        actix-web = { version = "4.0.0-beta.10" }
        

        【讨论】:

        • 谢谢。我恰好在 actix-web 中遇到了这个错误,并且正要令人失望地将我的 tokio 降级到 0.2。我更喜欢不太稳定的测试版而不是太旧的
        猜你喜欢
        • 1970-01-01
        • 2023-02-16
        • 1970-01-01
        • 1970-01-01
        • 2017-10-20
        • 2012-05-31
        • 1970-01-01
        • 1970-01-01
        • 2010-09-15
        相关资源
        最近更新 更多