diff --git a/Cargo.lock b/Cargo.lock index cbcd2cc..b2510b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1214,6 +1214,10 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c" +[[package]] +name = "socker" +version = "0.1.0" + [[package]] name = "strsim" version = "0.10.0" diff --git a/Cargo.toml b/Cargo.toml index 2caac63..7caa9f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "members/revsqrt", "members/serde-json-demo", "members/slog-demo", + "members/socker", ] default-members = [ ".", @@ -16,6 +17,7 @@ default-members = [ "members/slog-demo", "members/cucumber-demo", "members/panic-calm", + "members/socker", ] [package] diff --git a/members/socker/Cargo.toml b/members/socker/Cargo.toml new file mode 100644 index 0000000..3035cc3 --- /dev/null +++ b/members/socker/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "socker" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/members/socker/src/main.rs b/members/socker/src/main.rs new file mode 100644 index 0000000..7bad230 --- /dev/null +++ b/members/socker/src/main.rs @@ -0,0 +1,40 @@ +use std::{ + io::{BufRead, BufReader, Write}, + net::{TcpListener, TcpStream}, + process::exit, +}; + +fn main() { + println!("Starting the server"); + let target_address = "127.0.0.1:7878"; + let listener = match TcpListener::bind(target_address) { + Ok(listener) => listener, + Err(err) => { + eprintln!("Could not start server: {err}"); + exit(1); + } + }; + for stream in listener.incoming() { + let stream = stream.unwrap(); + + handle_connection(stream); + } +} + +fn handle_connection(mut stream: TcpStream) { + let buf_rd = BufReader::new(&mut stream); + let request: Vec<_> = buf_rd + .lines() + .map(|result| result.unwrap()) + .take_while(|line| !line.is_empty()) + .collect(); + println!("Request: {:#?}", request); + match request[0].as_str() { + "ping" => { + writeln!(stream, "> pong!").unwrap(); + } + _ => { + writeln!(stream, "> command not recognized.").unwrap(); + } + } +}