Work on server and client connectivity

This commit is contained in:
Michael Mikovsky
2025-06-06 19:20:49 -06:00
parent 92c9f08a5c
commit fda5e9ea02
28 changed files with 728 additions and 251 deletions
+54 -10
View File
@@ -1,6 +1,6 @@
use std::{
io::{self, BufRead, BufReader, Write},
net::{TcpListener, TcpStream},
net::{SocketAddr, TcpListener, TcpStream},
};
use crate::networkers::{ClientTrait, Connection, ServerTrait};
@@ -8,20 +8,43 @@ use crate::networkers::{ClientTrait, Connection, ServerTrait};
pub struct TCPConnection {
stream: TcpStream,
reader: BufReader<TcpStream>,
is_alive: bool,
}
impl Connection for TCPConnection {
type Error = io::Error;
fn get_info(&self) -> String {
format!(
"tcp://{}",
if let Ok(addr) = &self.stream.peer_addr() {
addr.to_string()
} else {
"ERROR".to_string()
}
)
}
fn is_alive(&self) -> bool {
self.is_alive
}
fn read(&mut self) -> Result<String, Self::Error> {
let mut line = String::new();
self.reader.read_line(&mut line)?;
let n = self.reader.read_line(&mut line)?;
// Stream sends a null buffer if it is disconnected
if n == 0 {
self.is_alive = false;
}
Ok(line.trim_end().to_string())
}
fn write(&mut self, data: &str) -> Result<(), Self::Error> {
writeln!(self.stream, "{}", data)?;
self.stream.flush()
self.stream.flush()?;
Ok(())
}
}
@@ -32,13 +55,28 @@ pub struct TCPServer {
impl ServerTrait<TCPConnection> for TCPServer {
type Error = io::Error;
fn accept(&mut self) -> Result<TCPConnection, Self::Error> {
let (stream, _) = self.listener.accept()?;
let reader = BufReader::new(stream.try_clone()?);
Ok(TCPConnection { stream, reader })
fn get_info(&self) -> String {
format!(
"tcp://{}",
if let Ok(addr) = &self.listener.local_addr() {
addr.to_string()
} else {
"ERROR".to_string()
}
)
}
fn bind(address: &str) -> Result<Self, Self::Error> {
fn accept(&self) -> Result<TCPConnection, Self::Error> {
let (stream, _) = self.listener.accept()?;
let reader = BufReader::new(stream.try_clone()?);
Ok(TCPConnection {
stream,
reader,
is_alive: true,
})
}
fn bind(address: &SocketAddr) -> Result<Self, Self::Error> {
let listener = TcpListener::bind(address)?;
Ok(Self { listener })
}
@@ -49,9 +87,15 @@ pub struct TCPClient;
impl ClientTrait<TCPConnection> for TCPClient {
type Error = io::Error;
fn connect(address: &str) -> Result<TCPConnection, Self::Error> {
fn connect(address: &SocketAddr) -> Result<TCPConnection, Self::Error> {
let stream = TcpStream::connect(address)?;
let reader = BufReader::new(stream.try_clone()?);
Ok(TCPConnection { stream, reader })
let conn = TCPConnection {
stream,
reader,
is_alive: true,
};
info!("Connected to {}", conn.get_info());
Ok(conn)
}
}