From 0d9d4983c61cebaa291b23724d3ed530b1ca6fd7 Mon Sep 17 00:00:00 2001 From: Unisko PENG Date: Thu, 30 Mar 2023 13:56:25 +0800 Subject: [PATCH] Update Ch20 --- hello/src/main.rs | 13 ++++--- ...ect_Building_a_Multithreaded_Web_Server.md | 35 ++++++++++++++++++- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/hello/src/main.rs b/hello/src/main.rs index bc7a713..3943105 100644 --- a/hello/src/main.rs +++ b/hello/src/main.rs @@ -3,6 +3,8 @@ use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, + thred, + time::Duration, }; fn main() { @@ -19,10 +21,13 @@ fn handle_conn(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let req_line = buf_reader.lines().next().unwrap().unwrap(); - let (status_line, filename) = if req_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 &req_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(); diff --git a/src/Ch20_Final_Project_Building_a_Multithreaded_Web_Server.md b/src/Ch20_Final_Project_Building_a_Multithreaded_Web_Server.md index 83e1e55..09db0e7 100644 --- a/src/Ch20_Final_Project_Building_a_Multithreaded_Web_Server.md +++ b/src/Ch20_Final_Project_Building_a_Multithreaded_Web_Server.md @@ -484,4 +484,37 @@ fn handle_conn(mut stream: TcpStream) { **Simulating a Slow Request in the Current Server Implemenation** -咱们将看看一个慢速处理的请求,能怎样应用到咱们当前服务器实现的其他请求。下面清单 20-10 以将导致服务器在响应前睡眠 5 秒的一个模拟慢速请求,实现了对到 `/sleep` 请求的处理。 +咱们将看看一个慢速处理的请求,能怎样影响那些到咱们当前服务器实现的其他请求。下面清单 20-10 以一个将导致服务器在响应前睡眠 5 秒的模拟慢速请求,实现了对到 `/sleep` 请求的处理。 + +文件名:`src/main.rs` + +```rust +#![allow(warnings)] +use std::{ + fs, + io::{prelude::*, BufReader}, + net::{TcpListener, TcpStream}, + thred, + time::Duration, +}; +// --跳过代码-- + +fn handle_conn(mut stream: TcpStream) { + // --跳过代码-- + + let (status_line, filename) = match &req_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"), + }; + + // --跳过代码-- +} +``` + +*清单 20-10:通过睡眠 5 秒模拟慢速请求* + +