liminality/src/client.rs

71 lines
2.1 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::{
env::args,
io::{ BufRead, BufReader, stdin, Write },
net::TcpStream,
thread,
};
use yacexits::exit;
fn main() {
let args = args().collect::<Vec<String>>();
let argv = args.iter().map(String::as_str).collect::<Vec<&str>>();
if !argv.clone().get(1).is_some() || !argv.clone().get(2).is_some() {
exit(1);
}
let user = argv[2];
let mut stream = TcpStream::connect(argv[1]).unwrap_or_else(|err| {
eprintln!("{:?}", err);
exit(1);
});
let from_message = format!("FROM {}\n", user);
let _ = stream.write(from_message.as_bytes());
let stream_recv = stream.try_clone().unwrap();
let _ = thread::spawn(move || {
let reader = BufReader::new(stream_recv);
for line in reader.lines() {
if let Ok(message) = line {
let words: Vec<&str> = message.split_whitespace().collect();
match words[0] {
"FROM" => print!("{}: ", words[1..].join(" ")),
"BODY" => println!("{}", words[1..].join(" ")),
_ => {},
}
}
}
});
loop {
let mut buf = String::new();
let _ = stdin().read_line(&mut buf);
let out = format!("BODY {}\n", buf);
let _ = stream.write(out.as_bytes());
}
}