From 09721310191abacdf41cbfa885f67a1646ad1c28 Mon Sep 17 00:00:00 2001 From: Unisko PENG Date: Thu, 30 Mar 2023 15:31:56 +0800 Subject: [PATCH] Update Ch20 --- hello/Cargo.lock | 7 +++++++ hello/src/main.rs | 4 ++-- ...inal_Project_Building_a_Multithreaded_Web_Server.md | 10 ++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 hello/Cargo.lock diff --git a/hello/Cargo.lock b/hello/Cargo.lock new file mode 100644 index 0000000..c3aedd7 --- /dev/null +++ b/hello/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "hello" +version = "0.1.0" diff --git a/hello/src/main.rs b/hello/src/main.rs index 3943105..e134057 100644 --- a/hello/src/main.rs +++ b/hello/src/main.rs @@ -3,7 +3,7 @@ use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, - thred, + thread, time::Duration, }; @@ -24,7 +24,7 @@ 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)); + thread::sleep(Duration::from_secs(10)); ("HTTP/1.1 200 0K", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), 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 09db0e7..c7d4f1b 100644 --- a/src/Ch20_Final_Project_Building_a_Multithreaded_Web_Server.md +++ b/src/Ch20_Final_Project_Building_a_Multithreaded_Web_Server.md @@ -517,4 +517,14 @@ fn handle_conn(mut stream: TcpStream) { *清单 20-10:通过睡眠 5 秒模拟慢速请求* +现在咱们有了三种情况,于是就已从 `if` 切换到了 `match`。咱们需要显式地在 `req_line` 切片上,与那三个字符串字面值进行模式匹配;`match` 不会像相等比较方式所做的那样,执行自动引用与解引用。 + +首条支臂与清单 20-9 的 `if` 代码块是一样的。第二条支臂,是将请求与 `/sleep` 匹配。在收到那个请求时,服务器将在渲染那个成功 HTML 页面之前,睡眠 5 秒。第三支臂则与清单 20-9 的那个 `else` 代码块是一样的。 + +咱们可以看出,咱们的服务器有多原始:真正的库将以一种不那么冗长的方式,处理多种请求的识别! + +请使用 `cargo run` 启动服务器。随后打开两个浏览器窗口:一个用于 `http://127.0.0.1/7878`,另一个用于 `http://127.0.0.1:7878/sleep`。若咱们像之前一样进入那个 `/` URI 几次,咱们将看到其响应很快。但在进入 `/sleep` 并于随后加载 `/` 时,就会看到那个 `/` 会一直等待,知道 `sleep` 已经于加载之前睡眠了 5 秒。 + +咱们可以用来避免慢速请求后面那些请求滞后的技巧有多种;咱们将实现的技巧,便是线程池。 +