Skip to content

Commit c14a26b

Browse files
committed
c20: spawn a thread for each request (OS can run out of resources)
1 parent 1f31a2c commit c14a26b

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

c20_web_server/src/main.rs

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
use std::{fs, io::{BufRead, BufReader, Write}, net::{TcpListener, TcpStream}};
1+
use std::{fs, io::{BufRead, BufReader, Write}, net::{TcpListener, TcpStream}, thread, time::Duration};
22

33

44
fn handle_connection(mut stream: TcpStream) {
55
let buf_reader = BufReader::new(&mut stream);
6-
let request_line = buf_reader.lines().next().unwrap().unwrap();
6+
let request_line: String = buf_reader.lines().next().unwrap().unwrap();
7+
eprint!("Handling request: {request_line}");
78

89
// let http_request: Vec<_> = buf_reader
910
// .lines()
@@ -12,24 +13,29 @@ fn handle_connection(mut stream: TcpStream) {
1213
// .collect();
1314
// println!("Request: {:#?}", http_request);
1415

15-
16-
let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
17-
("HTTP/1.1 200 OK", "hello.html")
18-
} else {
19-
("HTTP/1.1 404 NOT FOUND", "404.html")
16+
// must add & in front of request_line due to match unable to auto referencing and derefencing.
17+
let (status_line, filename) = match &request_line[..] {
18+
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
19+
"GET /sleep HTTP/1.1" => {
20+
thread::sleep(Duration::from_secs(5));
21+
("HTTP/1.1 200 OK", "hello.html")},
22+
_ => ("HTTP/1.1 404 NOT FOUND", "404.html")
2023
};
2124
let contents = fs::read_to_string(filename).unwrap();
2225
let length = contents.len();
2326
let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
24-
println!("Handling request {request_line}");
2527
stream.write_all(response.as_bytes()).unwrap();
28+
eprintln!(" Done.");
2629
}
30+
2731
fn main() {
28-
println!("{:#?}", &[0; 3]);
32+
// [0; 3] is [0,0,0];
33+
//println!("{:#?}", &[0; 3]);
34+
println!("Listening at TCP 127.0.0.1:7878.");
2935
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
3036
for stream in listener.incoming() {
3137
let stream = stream.unwrap();
3238

33-
handle_connection(stream);
39+
thread::spawn(|| { handle_connection(stream); });
3440
}
3541
}

0 commit comments

Comments
 (0)