Files
unshell-nodes-rs/unshell-rs-lib/src/networkers/tcp.rs
T

158 lines
4.2 KiB
Rust
Raw Normal View History

2025-06-04 22:52:20 -06:00
use std::{
io::{self, BufRead, BufReader, Write},
2025-06-06 19:20:49 -06:00
net::{SocketAddr, TcpListener, TcpStream},
2025-06-04 22:52:20 -06:00
};
2025-06-09 12:37:49 -06:00
use crate::{
Error,
networkers::{ClientTrait, Connection, ServerTrait},
};
2025-06-04 22:52:20 -06:00
pub struct TCPConnection {
stream: TcpStream,
reader: BufReader<TcpStream>,
2025-06-06 19:20:49 -06:00
is_alive: bool,
2025-06-04 22:52:20 -06:00
}
impl Connection for TCPConnection {
2025-06-06 19:20:49 -06:00
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
}
2025-06-09 12:37:49 -06:00
fn read(&mut self) -> Result<String, Error> {
2025-06-04 22:52:20 -06:00
let mut line = String::new();
2025-06-06 19:20:49 -06:00
let n = self.reader.read_line(&mut line)?;
// Stream sends a null buffer if it is disconnected
if n == 0 {
self.is_alive = false;
}
2025-06-04 22:52:20 -06:00
Ok(line.trim_end().to_string())
}
2025-06-09 12:37:49 -06:00
fn write(&mut self, data: &str) -> Result<(), Error> {
info!("Sent: {}", data);
2025-06-04 22:52:20 -06:00
writeln!(self.stream, "{}", data)?;
2025-06-06 19:20:49 -06:00
self.stream.flush()?;
Ok(())
2025-06-04 22:52:20 -06:00
}
}
2025-06-09 12:37:49 -06:00
// impl AsyncConnection<TCPConnection> for TCPConnection {
// type Error = io::Error;
// fn as_async<T: Serialize + DeserializeOwned + Send + 'static>(
// connection: TCPConnection,
// ) -> (Sender<T>, Receiver<T>) {
// let (send_tx, send_rx) = crossbeam_channel::unbounded::<T>();
// let (recv_tx, recv_rx) = crossbeam_channel::unbounded::<T>();
// thread::spawn(move || {
// let mut reader = connection.reader;
// let mut read = || -> Result<String, Self::Error> {
// let mut line = String::new();
// let _ = reader.read_line(&mut line)?;
// Ok(line.trim_end().to_string())
// };
// loop {
// if let Ok(data) = read() {
// if data.is_empty() {
// break;
// }
// info!("Got {}", data);
// if let Ok(decoded) = serde_json::from_str::<T>(&data) {
// if let Err(e) = send_tx.send(decoded) {
// error!("Got error: {}", e);
// }
// }
// }
// }
// });
// thread::spawn(move || {
// let mut stream = connection.stream;
// let mut write = |data: String| -> Result<(), Self::Error> {
// writeln!(stream, "{}", data)?;
// stream.flush()?;
// Ok(())
// };
// loop {
// if let Ok(data) = recv_rx.recv() {
// if let Ok(encoded) = serde_json::to_string(&data) {
// info!("Write {}", encoded);
// if let Err(e) = write(encoded) {
// error!("Got error: {}", e);
// }
// }
// }
// }
// });
// (recv_tx, send_rx)
// }
// }
2025-06-08 17:16:08 -06:00
2025-06-04 22:52:20 -06:00
pub struct TCPServer {
listener: TcpListener,
}
impl ServerTrait<TCPConnection> for TCPServer {
2025-06-06 19:20:49 -06:00
fn get_info(&self) -> String {
format!(
"tcp://{}",
if let Ok(addr) = &self.listener.local_addr() {
addr.to_string()
} else {
"ERROR".to_string()
}
)
}
2025-06-09 12:37:49 -06:00
fn accept(&self) -> Result<TCPConnection, Error> {
2025-06-04 22:52:20 -06:00
let (stream, _) = self.listener.accept()?;
let reader = BufReader::new(stream.try_clone()?);
2025-06-06 19:20:49 -06:00
Ok(TCPConnection {
stream,
reader,
is_alive: true,
})
2025-06-04 22:52:20 -06:00
}
2025-06-09 12:37:49 -06:00
fn bind(address: &SocketAddr) -> Result<Self, Error> {
2025-06-04 22:52:20 -06:00
let listener = TcpListener::bind(address)?;
Ok(Self { listener })
}
}
pub struct TCPClient;
impl ClientTrait<TCPConnection> for TCPClient {
2025-06-09 12:37:49 -06:00
fn connect(address: &SocketAddr) -> Result<TCPConnection, Error> {
2025-06-04 22:52:20 -06:00
let stream = TcpStream::connect(address)?;
let reader = BufReader::new(stream.try_clone()?);
2025-06-06 19:20:49 -06:00
let conn = TCPConnection {
stream,
reader,
is_alive: true,
};
Ok(conn)
2025-06-04 22:52:20 -06:00
}
}