我是 actix 的新手,我试图了解如何在一个线程上运行服务器并从另一个线程发送请求。
这是我到目前为止的代码
use actix_web::{web, App, HttpResponse, HttpServer};
use std::{sync::mpsc::channel, thread};
#[actix_web::main]
async fn main() {
let (tx, rx) = channel();
thread::spawn(move || {
let srv =
HttpServer::new(|| App::new().default_service(web::to(|| HttpResponse::NotFound())))
.bind("localhost:12347")
.unwrap()
.run();
let _ = tx.send(srv);
});
reqwest::get("http://localhost:12347").await.unwrap();
let srv = rx.recv().unwrap();
srv.handle().stop(false).await;
}
Run Code Online (Sandbox Code Playgroud)
它编译得很好,但在发送请求时卡住了。看起来服务器正在运行,所以我不明白为什么我没有得到响应。
编辑:按照@Finomnis和@cafce25的建议,我更改了代码以使用任务而不是线程,并await编辑了结果.run()
use actix_web::{web, App, HttpResponse, HttpServer};
use std::{sync::mpsc::channel, thread};
#[actix_web::main]
async fn main() {
let (tx, rx) = channel();
tokio::spawn(async move {
let srv =
HttpServer::new(|| App::new().default_service(web::to(|| HttpResponse::NotFound())))
.bind("localhost:12347")
.unwrap() …Run Code Online (Sandbox Code Playgroud)