» Rust: Make Web Chat App with Socket.IO » 2. Development » 2.1 Initial Version

Initial Version

Create a package

Run the cargo new command:

cargo new lr_webchat_rs --bin

We’re passing --bin because we’re making a binary program: if we were making a library, we’d pass --lib.

Or, if you want to create a binary Cargo package in an existing directory:

cargo init

This command creates start files, including the Cargo.toml file, where you can list the dependencies you add for tracking.

Add dependencies

Install socketioxide, tower, tower-http, axum and tokio dependencies:

Run the cargo add command:

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"

Or, add dependencies in 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"] }

Update 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(())
}

Run the program like this:

cargo run

Output:

   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

Your chat server is running on port 4000 now.

PrevNext