Updated 'src/final_project/mutlithreaded.md'.

This commit is contained in:
Hector PENG
2026-04-27 17:06:27 +08:00
parent 3f64545388
commit c759565d52
2 changed files with 61 additions and 54 deletions

View File

@@ -1,16 +1,21 @@
use std::{
fs,
io::{BufReader, prelude::*},
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
thread,
time::Duration,
};
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream);
pool.execute(|| {
handle_connection(stream);
});
}
}
@@ -18,12 +23,16 @@ fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ( "HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 0K", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();