我正在将 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 保持活力和快乐。