Why is it that the connection handler does not run in parallel when the same endpoint is visited?

use std::{
    fs,
    io::{prelude::*, BufReader},
    net::{TcpListener, TcpStream}, thread::{self, sleep}, time::Duration,
};
fn main() {
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        thread::spawn(|| {
            handle_connection(stream);
        });
    }
}
fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&stream);
    let request_line = buf_reader.lines().next().unwrap().unwrap();

    if request_line == "GET / HTTP/1.1" {
        let status_line = "HTTP/1.1 200 OK";
        let contents = fs::read_to_string("hello.html").unwrap();
        let length = contents.len();

        let response = format!(
            "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
        );

        stream.write_all(response.as_bytes()).unwrap();
    } else {
        sleep(Duration::from_secs(1)); 
        println!("1");
        sleep(Duration::from_secs(1)); 
        println!("2");
        sleep(Duration::from_secs(1)); 
        println!("3");
        let status_line = "HTTP/1.1 200 OK"; 
        let contents = "24123213213"; 
        let length = contents.len(); 
        let response = format!(
            "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"
        );

        stream.write_all(response.as_bytes()).unwrap();
    }
}

For the code above, if I visit /aaa and /bbb at the same time on a different device, the output is

1
1
2
2
3
3

However if I visit /aaa and /aaa on different devices, the output is

1
2
3
1
2
3

Where one thread is blocking another.

However they are using the same function, so I don't think it is a problem with resources being used at another thread.

I have tried to use Tokio in my original project (the code above is not my original project, this is a simplified version), but the problem persists.

How I am able to fix this, or this is a problem regarding HTTP 1.1?

Upvotes: 0

Views: 44

Answers (0)

Related Questions