-1

我正在将 Warp 板条箱用于 Web 服务,但在从我的非异步主服务器运行它时遇到问题。

我尝试了几种方法,我得到的最接近的是:

货运.toml

[dependencies]
warp = "0.3"
futures = "0.3"

代码:

use std::collections::HashMap;
use std::thread::{sleep, spawn};
use std::time;
use warp::{Filter};
use futures::executor::block_on;

async fn get_ap_list() -> Result<impl warp::Reply, warp::Rejection> {
    let mut result = HashMap::new();

    // TODO: Get a full list
    result.insert("SSID", "rossless_24");

    Ok(warp::reply::json(&result))
}

async fn start_ap_server() {
    println!("AP server");

    let get_ap = warp::get()
        .and(warp::path("ap"))
        .and(warp::path("list"))
        .and(warp::path::end())
        .and_then(get_ap_list);

    warp::serve(get_ap)
       .run(([0, 0, 0, 0], 3030))
        .await;
}

// This intermediate function seem a bit redundant but I can't seem to spawn the async server directly
fn init_ap_server() {
    println!("Init AP server");

    let future = start_ap_server();
    block_on(future);
}

fn main() {
    let _t1 = spawn(move || {
        init_ap_server()
        });

    // Make sure main is still running
    loop {
        println!("Alive for test.");
        sleep(time::Duration::from_millis(5000));
    }
}

这似乎有效,但我得到:

thread '<unnamed>' panicked at 'there is no reactor running, must be called from the context of a Tokio 1.x runtime', /home/tross/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.5.0/src/runtime/context.rs:18:26

谷歌搜索我发现它可能是 Tokio 版本不匹配,但我的依赖项中什至没有 Tokio,我是从 Warp 获得的。

退一步,有没有更简单的方法来得到我想要的?我只想启动一些运行的异步代码(可能在它自己的线程上),同时让 main 保持活力和快乐。

4

1 回答 1

2

warp它本身确实引入了tokio依赖项,但它没有附带以下rt功能:

// warp/Cargo.toml
...
tokio = { version = "1.0", features = ["fs", "sync", "time"] }
...

所以没有运行时来执行期货。为了获得 atokio::Runtime您可以显式生成 aRuntimeblock_on在该运行时调用:

// This intermediate function seem a bit redundant but I can't seem to spawn the async server directly
fn init_ap_server() {
    println!("Init AP server");
    let runtime = Builder::new_current_thread()
        .enable_io()
        .build()
        .expect("Failed to create runtime");

    let future = start_ap_server();
    runtime.block_on(future);
}

和:

[dependencies]
warp = "0.3"
tokio = {version = "1", features = ["rt"] }
于 2021-04-27T14:43:52.170 回答