小编141*_*159的帖子

在单独的线程上运行 actix Web 服务器

我是 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)

rust actix-web

3
推荐指数
1
解决办法
1919
查看次数

标签 统计

actix-web ×1

rust ×1