1
Fork 0

Use buffer to ensure only 1 line is read

This commit is contained in:
Jake Howard 2023-08-20 11:29:07 +01:00
parent 3369862d8d
commit 2aa154100c
Signed by: jake
GPG key ID: 57AFB45680EDD477

View file

@ -1,7 +1,7 @@
use rand::{thread_rng, RngCore}; use rand::{thread_rng, RngCore};
use std::env; use std::env;
use std::fs::remove_file; use std::fs::remove_file;
use std::io::{BufRead, BufReader, Read, Write}; use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::{UnixListener, UnixStream}; use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
@ -61,46 +61,40 @@ fn create_socket() -> PathBuf {
temp_dir temp_dir
} }
fn handle_client(mut stream: UnixStream) { fn handle_client(stream: UnixStream) {
let start_time = SystemTime::now();
const TIMEOUT: Duration = Duration::from_secs(3); const TIMEOUT: Duration = Duration::from_secs(3);
stream let reader = BufReader::new(stream.try_clone().unwrap());
.set_read_timeout(Some(Duration::from_millis(1)))
.unwrap();
loop { stream.set_read_timeout(Some(TIMEOUT)).unwrap();
let mut response = String::new();
// Change to use buffered, read line until timeout, and catch timeout as below (hopefully can change timeout after initial read) let mut lines = reader.lines();
match stream.read_to_string(&mut response) { match lines.next() {
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} Some(Err(e)) if e.kind() == std::io::ErrorKind::WouldBlock => {
Err(e) => { println!("Timeout");
println!("Error reading {}", e); return;
} }
_ => {} Some(Err(e)) => {
} println!("Error reading {}", e);
return;
if response.trim_end() == "handshake" { }
println!("Got correct handshake"); Some(Ok(msg)) => {
break; if msg != "handshake" {
} println!("Got incorrect handshake: {:?}", msg);
return;
if SystemTime::now().duration_since(start_time).unwrap() >= TIMEOUT { }
println!("Timeout expired, killing connection"); println!("Got correct handshake");
}
None => {
return; return;
} }
// thread::sleep(Duration::from_secs(1));
} }
// Restore blocking socket for increased efficiency
stream.set_read_timeout(None).unwrap(); stream.set_read_timeout(None).unwrap();
let reader = BufReader::new(stream); for line in lines {
for line in reader.lines() {
dbg!(line.unwrap()); dbg!(line.unwrap());
} }