From 28382b249535e964ce983fe5a0821a898a077775 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sat, 28 Feb 2026 17:35:40 +0100 Subject: multi file for both sides --- src/bin/client/connection.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/bin/client/connection.rs (limited to 'src/bin/client/connection.rs') diff --git a/src/bin/client/connection.rs b/src/bin/client/connection.rs new file mode 100644 index 0000000..9e402cb --- /dev/null +++ b/src/bin/client/connection.rs @@ -0,0 +1,32 @@ +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpStream; +use std::sync::mpsc; +use std::thread; +use std::time::{Duration, Instant}; + +pub fn connect(addr: &str) -> Result> { + let (tx, rx) = mpsc::channel(); + let addr_str = addr.to_string(); + thread::spawn(move || { + match TcpStream::connect(&addr_str) { + Ok(s) => tx.send(Ok(s)).unwrap(), + Err(e) => tx.send(Err(e)).unwrap(), + } + }); + match rx.recv_timeout(Duration::from_secs(3)) { + Ok(Ok(s)) => { + let mut ping_writer = s.try_clone().unwrap(); + let mut ping_reader = BufReader::new(s.try_clone().unwrap()); + let start = Instant::now(); + writeln!(ping_writer, "PING").unwrap(); + let mut response = String::new(); + ping_reader.read_line(&mut response).unwrap(); + let elapsed = start.elapsed(); + println!("Connected to {} with ping delay: {:?}", addr, elapsed); + Ok(s) + } + Ok(Err(e)) => Err(Box::new(e)), + Err(mpsc::RecvTimeoutError::Timeout) => Err("Connection timed out after 3 seconds".into()), + Err(_) => Err("Connection attempt failed".into()), + } +} -- cgit v1.2.3