From 9f01e334e13af694852539882e0b6b9543826311 Mon Sep 17 00:00:00 2001 From: CrispyPin Date: Sat, 4 Jun 2022 19:22:41 +0200 Subject: [PATCH] init --- .gitignore | 1 + Cargo.lock | 7 +++++++ Cargo.toml | 8 ++++++++ src/main.rs | 38 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..4e6b218 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "webserver" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..1187bc1 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "webserver" +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/src/main.rs b/src/main.rs new file mode 100644 index 0000000..b98d654 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,38 @@ +use std::{net::{TcpStream, TcpListener}, io::prelude::*, fs}; + + +fn main() { + let listener = TcpListener::bind("192.168.0.108:25585").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + println!("IP: {}\n", stream.peer_addr().unwrap()); + + handle_connection(stream); + } +} + + +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 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.flush().unwrap(); + println!("read {} bytes:\n{}", size, + String::from_utf8_lossy(&buffer) + .escape_debug() + .collect::() + .replace("\\r\\n", "\n") + .replace("\\n", "\n") + ); +}