Skip to content

Commit 69c105e

Browse files
authored
Merge pull request #20 from hide5stm/2_4_4
add 2_4_4/server.rs
2 parents 3f5218e + c326b9e commit 69c105e

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

chapter2/Cargo.toml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,8 @@ path = "src/2_4_2/main.rs"
1818

1919
[[bin]]
2020
name = "client_2_4_4"
21-
path = "src/2_4_4/client.rs"
21+
path = "src/2_4_4/client.rs"
22+
23+
[[bin]]
24+
name = "server_2_4_4"
25+
path = "src/2_4_4/server.rs"

chapter2/src/2_4_4/server.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use std::io::{BufRead, BufReader, Write};
2+
use std::net::{TcpListener, TcpStream};
3+
4+
fn get_operation(stream: &mut TcpStream) -> std::io::Result<()> {
5+
let body = "HTTP server sample";
6+
writeln!(stream, "HTTP/1.1 200 OK")?;
7+
writeln!(stream, "Content-Type: text/plain; charset=UTF-8")?;
8+
writeln!(stream, "Content-Length: {}", body.len())?;
9+
writeln!(stream)?;
10+
11+
writeln!(stream, "{}", body)?;
12+
Ok(())
13+
}
14+
15+
fn handle_client(stream: TcpStream) -> std::io::Result<()> {
16+
let mut reader = BufReader::new(stream);
17+
18+
let mut first_line = String::new();
19+
reader.read_line(&mut first_line)?;
20+
21+
let mut params = first_line.split_whitespace();
22+
let method = params.next();
23+
let path = params.next();
24+
match (method, path) {
25+
(Some("GET"), Some(_)) => {
26+
get_operation(reader.get_mut())?;
27+
}
28+
_ => panic!("failed to parse"),
29+
}
30+
Ok(())
31+
}
32+
33+
fn main() -> std::io::Result<()> {
34+
let listener = TcpListener::bind("127.0.0.1:8080")?;
35+
36+
for stream in listener.incoming() {
37+
handle_client(stream?)?;
38+
}
39+
Ok(())
40+
}

0 commit comments

Comments
 (0)