summaryrefslogtreecommitdiffstats
path: root/src/bin/client/connection.rs
diff options
context:
space:
mode:
authorsalmonik <raisersoft@proton.me>2026-02-28 17:35:40 +0100
committersalmonik <raisersoft@proton.me>2026-02-28 17:35:40 +0100
commit28382b249535e964ce983fe5a0821a898a077775 (patch)
tree3b68dd13d9fec27ab3163f09285c718874540c65 /src/bin/client/connection.rs
parentinit version (diff)
downloadzagan-bet-28382b249535e964ce983fe5a0821a898a077775.tar.gz
zagan-bet-28382b249535e964ce983fe5a0821a898a077775.zip
multi file for both sides
Diffstat (limited to 'src/bin/client/connection.rs')
-rw-r--r--src/bin/client/connection.rs32
1 files changed, 32 insertions, 0 deletions
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 @@
1use std::io::{BufRead, BufReader, Write};
2use std::net::TcpStream;
3use std::sync::mpsc;
4use std::thread;
5use std::time::{Duration, Instant};
6
7pub fn connect(addr: &str) -> Result<TcpStream, Box<dyn std::error::Error>> {
8 let (tx, rx) = mpsc::channel();
9 let addr_str = addr.to_string();
10 thread::spawn(move || {
11 match TcpStream::connect(&addr_str) {
12 Ok(s) => tx.send(Ok(s)).unwrap(),
13 Err(e) => tx.send(Err(e)).unwrap(),
14 }
15 });
16 match rx.recv_timeout(Duration::from_secs(3)) {
17 Ok(Ok(s)) => {
18 let mut ping_writer = s.try_clone().unwrap();
19 let mut ping_reader = BufReader::new(s.try_clone().unwrap());
20 let start = Instant::now();
21 writeln!(ping_writer, "PING").unwrap();
22 let mut response = String::new();
23 ping_reader.read_line(&mut response).unwrap();
24 let elapsed = start.elapsed();
25 println!("Connected to {} with ping delay: {:?}", addr, elapsed);
26 Ok(s)
27 }
28 Ok(Err(e)) => Err(Box::new(e)),
29 Err(mpsc::RecvTimeoutError::Timeout) => Err("Connection timed out after 3 seconds".into()),
30 Err(_) => Err("Connection attempt failed".into()),
31 }
32}