summaryrefslogtreecommitdiff
path: root/rust-book/hello_server/src/bin
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-27 15:32:37 -0400
commit67cdcc2e12118becb823e20a40cc2687f2b8425a (patch)
treeed92c3234b89079e6d4cf36f5e80c5ffa79def48 /rust-book/hello_server/src/bin
parente25482fca375d318a39c3b54db396b0db6e0b263 (diff)
downloadlearning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.tar.xz
learning-rust-67cdcc2e12118becb823e20a40cc2687f2b8425a.zip
Started Rust in Action MEAP.
Diffstat (limited to 'rust-book/hello_server/src/bin')
-rwxr-xr-xrust-book/hello_server/src/bin/main.rs46
1 files changed, 46 insertions, 0 deletions
diff --git a/rust-book/hello_server/src/bin/main.rs b/rust-book/hello_server/src/bin/main.rs
new file mode 100755
index 0000000..bcf1e46
--- /dev/null
+++ b/rust-book/hello_server/src/bin/main.rs
@@ -0,0 +1,46 @@
+use hello_server::ThreadPool;
+use std::thread;
+use std::time::Duration;
+use std::io::prelude::*;
+use std::fs;
+use std::net::TcpStream;
+use std::net::TcpListener;
+
+fn main() {
+ let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
+ let pool = ThreadPool::new(4).unwrap();
+
+ for stream in listener.incoming().take(2) {
+ let stream = stream.unwrap();
+
+ pool.execute(|| {
+ handle_connection(stream);
+ });
+ }
+
+ println!("shutting down...");
+
+}
+
+fn handle_connection(mut stream: TcpStream) {
+ let mut buffer = [0; 512];
+ stream.read(&mut buffer).unwrap();
+ let get = b"GET / HTTP/1.1\r\n";
+ let sleep = b"GET /sleep HTTP/1.1\r\n";
+
+ let (status_line, filename) = if buffer.starts_with(get) {
+ ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
+ }
+ else if buffer.starts_with(sleep) {
+ thread::sleep(Duration::from_secs(5));
+ ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
+ }
+ else {
+ ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
+ };
+
+ let contents = fs::read_to_string(filename).unwrap();
+ let response = format!("{}{}", status_line, contents);
+ stream.write(response.as_bytes()).unwrap();
+ stream.flush().unwrap();
+}