box-o-sand/rustbook/httpong/src/main.rs

38 lines
964 B
Rust
Raw Normal View History

2021-06-01 12:49:27 +00:00
use std::env;
2021-06-01 14:27:17 +00:00
use std::io::Read;
2021-06-01 12:49:27 +00:00
use std::net::{TcpListener, TcpStream};
2021-06-01 14:27:17 +00:00
fn handle_client(stream: &mut TcpStream) -> std::io::Result<()> {
2021-06-01 12:49:27 +00:00
println!("---> handling stream {:?}", stream);
2021-06-01 14:27:17 +00:00
let mut buf = [0; 1024];
let n = stream.read(&mut buf[..])?;
let req = std::str::from_utf8(&buf[..n]);
match req {
Ok(s) => {
println!("---> first {} bytes: {:?}", n, s);
Ok(())
}
Err(e) => {
println!("---> oh no {:?}", e);
Ok(())
}
}
2021-06-01 12:49:27 +00:00
}
fn main() -> std::io::Result<()> {
let mut addr = String::from("127.0.0.1:19721");
if let Ok(v) = env::var("ADDR") {
addr = String::from(v.as_str());
}
println!("listening at {}", addr);
let listener = TcpListener::bind(addr)?;
for stream in listener.incoming() {
2021-06-01 14:27:17 +00:00
if let Ok(_) = handle_client(&mut stream?) {
println!("---> looks like that went well")
}
2021-06-01 12:49:27 +00:00
}
Ok(())
}