Deep dive HTTP server with tokio rust

Alex Nguyen2023/11/05i did itrust

source code

use std::net::SocketAddr;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
async fn process_socket(socket: TcpStream, adr: SocketAddr) {
    // do work with socket here
    println!(
        "some socket connected  {} {}",
        adr.port(),
        socket.local_addr().unwrap()
    );

    let (mut r, mut w) = tokio::io::split(socket);

    let mut x = r"HTTP/1.1 200 OK
Date: Sun, 05 Nov 2023 14:26:21 GMT
Content-Type: text/html
Content-Length: LEN
Connection: close

";
    let data = r"<html>
<head><title>Alex</title></head>
<body>
<center><h1>Hello world</h1></center>
</body>
</html>";

    let mut buf = vec![0; 1000];
    let n = r.read(&mut buf).await.unwrap();
    if n == 0 {
        return;
    }
    println!("n is {n}");
    println!(
        "GOT:\n{}",
        String::from_utf8_lossy(&buf[..n]).replace("\r\n", "\n")
    );

    let mut x = format!("{x}{data}");
    x = x.replace("LEN", data.len().to_string().as_str());
    println!("send back \n{x}");

    w.write_all(x.as_bytes()).await.unwrap();
    w.shutdown().await.unwrap();
}

#[tokio::main]
async fn main() {
    let listener = TcpListener::bind("0.0.0.0:9999").await.unwrap();
    listener.set_ttl(100).unwrap();

    loop {
        let (socket, adr) = listener.accept().await.unwrap();
        tokio::spawn(async move { process_socket(socket, adr).await });
    }
}


with cargo.toml

[package]
name = "simple tcp server"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = {version = "1.33.0", features = ["full"]}

Last Updated 11/5/2023, 9:53:10 PM