初始版本
创建项目
执行 cargo new
命令:
cargo new lr_webchat_rs --bin
指定 --bin
参数用于制作二进制程序;如果制作库,可指定 --lib
参数。
或者,在已有目录里创建一个二进制 Cargo 项目:
cargo init
该命令会创建一系列初始文件,包括 Cargo.toml
文件,其主要用于追踪管理项目依赖。
添加依赖
安装 socketioxide
, tower
, tower-http
, axum
和 tokio
依赖:
执行 cargo add
:
cargo add socketioxide --features "extensions state"
cargo add axum
cargo add tower --no-default-features
cargo add tower-http --features cors
cargo add tokio --features "rt-multi-thread macros"
或者,添加依赖项到 Cargo.toml:
@@ -6,3 +6,5 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+axum = "0.7.5"
+socketioxide = { version = "0.13.1", features = ["extensions", "state"] }
+tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] }
+tower = { version = "0.4.13", default-features = false }
+tower-http = { version = "0.5.2", features = ["cors"] }
更新 src/main.rs:
use socketioxide::{extract::SocketRef, SocketIo};
use tower::ServiceBuilder;
use tower_http::cors::CorsLayer;
const PORT: i32 = 4000;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (layer, io) = SocketIo::builder().build_layer();
io.ns("/", |s: SocketRef| println!("A user connected {}", s.id));
let app = axum::Router::new().layer(
ServiceBuilder::new()
.layer(CorsLayer::permissive())
.layer(layer),
);
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", PORT))
.await
.unwrap();
println!("Chat server serving at localhost:{}", PORT);
axum::serve(listener, app).await.unwrap();
Ok(())
}
如下运行程序:
cargo run
将得到类似如下信息:
Compiling lr_webchat_rs v0.1.0 (~/projects/lr_webchat_rs)
Finished dev [unoptimized + debuginfo] target(s) in 1.71s
Running `target/debug/lr_webchat_rs`
Chat server serving at localhost:4000
你的 chat 服务器已经在 4000 端口跑起来了。