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]?

為{幸葍}努か 提交于 2021-02-04 17:18:22

问题


I'm following the mdns Rust documentation and pasted the example code but it throws the following error:

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

Here's the code that I have:

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:

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

What am I missing? I tried looking online but haven't found how to create a reactor for this use case.


回答1:


You are using a newer version of Tokio, such as 0.3 or 1.0 and many packages, including mdns 1.1.0, rely on an older version of Tokio, such as 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

For now, you will need to match versions of the Tokio runtime. The easiest way is to use Tokio 0.2 yourself. The tokio-compat-02 crate may also be useful in some cases.

See also:

  • Why is a trait not implemented for a type that clearly has it implemented?

Various error messages with the same root cause:

there is no reactor running, must be called from the context of Tokio runtime

not currently running on the Tokio runtime



来源:https://stackoverflow.com/questions/64779920/why-do-i-get-the-error-there-is-no-reactor-running-must-be-called-from-the-con

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!