From f6ac3e60a9c8cdf4feeaf8e699105a747caa7d37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vili=20Sinerv=C3=A4?= Date: Sat, 18 Jan 2025 12:51:26 +0200 Subject: [PATCH] Rust TCP/JSON server implementation --- Cargo.lock | 9 +++++++++ Cargo.toml | 1 + src/main.rs | 4 +++- src/server.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/server.rs diff --git a/Cargo.lock b/Cargo.lock index eda99a3..98dcbec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,3 +5,12 @@ version = 3 [[package]] name = "compiler-course" version = "0.1.0" +dependencies = [ + "json", +] + +[[package]] +name = "json" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" diff --git a/Cargo.toml b/Cargo.toml index 051fa55..551a6be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,3 +4,4 @@ version = "0.1.0" edition = "2021" [dependencies] +json = "0.12.4" diff --git a/src/main.rs b/src/main.rs index e7a11a9..bdc4a37 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +mod server; + fn main() { - println!("Hello, world!"); + server::start("::".parse().unwrap(), 3000); } diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..f731a92 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,42 @@ +use json; +use std::{ + io::prelude::*, + net::{IpAddr, TcpListener, TcpStream}, + thread, +}; + +pub fn start(address: IpAddr, port: u16) { + let address_string = format!("{address}:{port}"); + + let listener = TcpListener::bind(&address_string).unwrap_or_else(|error| { + panic!("Problem starting listener: {error:?}"); + }); + + println!("Listening for connections on {address_string}"); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + + thread::spawn(|| { + handle_connection(stream); + }); + } +} + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = String::new(); + stream + .read_to_string(&mut buffer) + .expect("Unable to read from buffer!"); + + let json_request = json::parse(&buffer).expect("Malformed JSON!"); + + match json_request["command"].as_str().unwrap() { + "ping" => println!("ping"), + "compile" => { + let program = &json_request["code"].as_str().unwrap(); + println!("compile code:\n\n{program}\n"); + } + _ => panic!("Unexpected command!"), + } +}