You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust Actix-Web后端curl连接失败求助:无法连接远程服务器

问题描述

我是Rust新手,尝试使用Rust结合Actix-Web框架搭建简单后端,但反复遇到连接失败问题。执行curl 127.0.0.1:8000/home命令时,提示错误:curl : Unable to connect to the remote server。已尝试查阅资料解决但未果,以下是我的代码:

main.rs

use actix_web::{web::Path, get, HttpServer, App, Responder};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
   let server= HttpServer::new(|| {
        App::new()
            .service(home)
            .service(hello_user)
    })
    .bind(("127.0.0.1",8000))?
    .run();
    println!("Server Running at 127");

     server.await 
    
}

#[get("/home")]
async fn home() -> impl Responder {
    let response: &str = "Welcome to actix server";
    response
}

#[get("/hello/{firstname}/{lastname}")]
async fn hello_user(params: Path<(String, String)>) -> impl Responder {
    let response: String = format!("Hello {} {}", params.0, params.1);
    response
}

Cargo.toml

[package]
name = "web-actix-server"
version = "0.1.0"
edition = "2021"

[dependencies]
actix-web = "4.2.1"

请求帮助排查并解决该问题。


解决方案

你的代码逻辑本身无错误,连接失败大概率是运行环境或启动时机问题,按以下步骤排查:

  • 检查端口占用:8000端口可能被其他程序占用,导致Actix服务器无法绑定端口。
    • Windows:执行 netstat -ano | findstr :8000,找到占用端口的进程PID,在任务管理器中结束该进程。
    • Linux/macOS:执行 lsof -i :8000,然后用 kill <PID> 终止对应进程。
  • 等待服务器完全启动:代码中println!("Server Running at 127")是在服务器启动前打印的,此时服务器还未开始监听端口。看到打印信息后不要立刻执行curl,等待1-2秒再尝试请求。若想让打印在服务器启动后触发,可调整代码顺序:
    #[actix_web::main]
    async fn main() -> std::io::Result<()> {
        let server = HttpServer::new(|| {
            App::new()
                .service(home)
                .service(hello_user)
        })
        .bind(("127.0.0.1", 8000))?
        .run();
        println!("Server Running at http://127.0.0.1:8000");
        server.await
    }
    
  • 排查防火墙拦截:Windows防火墙或第三方安全软件可能拦截了本地8000端口的连接,临时关闭防火墙后测试是否能正常连接。若可行,添加Actix程序的防火墙允许规则。
  • 修改绑定地址(可选):若需要让其他设备访问后端,可将绑定地址改为0.0.0.0,服务器会监听所有网卡,本地依然可用127.0.0.1:8000访问:
    .bind(("0.0.0.0", 8000))?
    

内容的提问来源于stack exchange,提问作者Shorna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:23:17