mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2025-03-14 03:10:44 +08:00
Update Ch20
This commit is contained in:
parent
0d9d4983c6
commit
0972131019
7
hello/Cargo.lock
generated
Normal file
7
hello/Cargo.lock
generated
Normal file
@ -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"
|
@ -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"),
|
||||
|
@ -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 秒。
|
||||
|
||||
咱们可以用来避免慢速请求后面那些请求滞后的技巧有多种;咱们将实现的技巧,便是线程池。
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user