liminality/src/main.rs
2023-06-17 14:30:53 -06:00

92 lines
2.5 KiB
Rust

/*
* Copyright (c) 2023 Emma Tebibyte
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
use std::{
io::{ self, BufRead, BufReader, Write },
net::{ TcpListener, TcpStream },
thread,
};
struct Message {
from: Option<String>,
body: Option<String>,
}
fn handle_client(stream: TcpStream) {
let mut reader = BufReader::new(&stream);
let mut writer = &stream;
let mut message = Message {
from: None,
body: None,
};
loop {
let mut send = false;
let mut buffer = String::new();
if reader.read_line(&mut buffer).is_err() {
println!(
"{} disconnected.",
message.from.unwrap_or_else(|| { format!("anon") }),
);
break;
}
let words: Vec<&str> = buffer.split_whitespace().collect();
if words.is_empty() {
continue;
}
match words[0] {
"FROM" => {
message.from = Some(words[1..].join(" "));
}
"BODY" => {
message.body = Some(words[1..].join(" "));
send = true;
}
_ => {}
}
if send {
println!(
"{}: {}",
message.from.clone().unwrap_or_else(|| { format!("anon") }),
message.body.take().unwrap(),
);
}
}
}
fn main() {
let listener = TcpListener::bind("0.0.0.0:8080")
.expect("Failed to bind to port 8080.");
println!("Server listening on port 8080.");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || handle_client(stream));
}
Err(e) => {
eprintln!("Error accepting client connection: {}", e);
}
}
}
}