From 5c5496fbb7cfbf75e17659e3d4c53aeafeae3c2e Mon Sep 17 00:00:00 2001 From: CrispyPin Date: Sun, 5 Jun 2022 20:45:19 +0200 Subject: [PATCH] add argument for port and ip, cleanup --- src/main.rs | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index b98d654..184f1a3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,25 @@ -use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs}; +use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs, env}; fn main() { - let listener = TcpListener::bind("192.168.0.108:25585").unwrap(); + let args: Vec = env::args().collect(); + + let host = if args.len() < 2 { + "127.0.0.1:6666" + } else { + &args[1] + }; + println!("Starting server on {:?}...\n", &host); + + let listener = TcpListener::bind(host).expect("Could not bind to address"); for stream in listener.incoming() { - let stream = stream.unwrap(); - println!("IP: {}\n", stream.peer_addr().unwrap()); - - handle_connection(stream); + if let Ok(stream) = stream { + handle_connection(stream); + } + else { + println!("Error with incoming stream: {}", stream.err().unwrap()); + } } } @@ -17,18 +28,20 @@ fn handle_connection(mut stream: TcpStream) { let mut buffer = vec![0; 1024]; let size = stream.read(&mut buffer).unwrap(); buffer.resize(size, 0); - let contents = fs::read_to_string("src/main.rs").unwrap(); + + let contents = fs::read_to_string("src/main.rs").unwrap() + "\n\n"; let response = format!( "HTTP/1.1 200 OK\nContent-Length: {}\n\n{}", contents.len() + buffer.len(), contents ); - - stream.write(response.as_bytes()).unwrap(); - stream.write(&buffer).unwrap(); + stream.write_all(response.as_bytes()).unwrap(); + stream.write_all(&buffer).unwrap(); stream.flush().unwrap(); - println!("read {} bytes:\n{}", size, + + let peer_addr = stream.peer_addr().unwrap(); + println!("Received {} bytes from {}\n\n{}\n", size, peer_addr, String::from_utf8_lossy(&buffer) .escape_debug() .collect::()