Reading and writing

This commit is contained in:
2025-08-12 14:36:19 -04:00
parent 708f85663a
commit fb97737a29
3 changed files with 60 additions and 64 deletions
+26 -41
View File
@@ -5,37 +5,25 @@ use std::{
use crate::route_tcp;
/// Prints a log message with a timestamp.
fn log(msg: &str) {
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let seconds = now.as_secs();
let millis = now.subsec_millis();
// Rough human-readable formatting: seconds since epoch + milliseconds
println!("[{}.{:03}] {}", seconds, millis, msg);
}
pub fn router() {
let listener = TcpListener::bind("0.0.0.0:7879").unwrap();
log("Router started on port 7879");
println!("Router started on port 7879");
for stream in listener.incoming() {
match stream {
Ok(mut client_recv) => {
log(&format!(
std::thread::spawn(|| {
println!(
"Incoming connection from {}",
client_recv.peer_addr().unwrap()
));
);
let mut address = [0; 6];
let bytes_read = client_recv.read(&mut address).unwrap();
if bytes_read == 0 {
log("Client disconnected before sending address.");
continue;
println!("Client disconnected before sending address.");
}
log(&format!("Received target address: {:?}", address));
println!("Received target address: {:?}", address);
let address = format!(
"{}.{}.{}.{}:{}",
@@ -46,26 +34,29 @@ pub fn router() {
u16::from_be_bytes([address[4], address[5]])
);
log(&format!("Connecting to routed server at {address}"));
println!("Connecting to routed server at {address}");
let mut client_send = client_recv.try_clone().unwrap();
let mut server_recv = TcpStream::connect(&address).unwrap();
let mut server_send = server_recv.try_clone().unwrap();
log(&format!("Connected to routed server at {address}"));
println!("Connected to routed server at {address}");
// Client -> Server
std::thread::spawn(move || {
while !route_tcp(&mut client_recv, &mut server_send) {}
log("Client -> Server routing stopped");
server_send.shutdown(Shutdown::Both).unwrap();
println!("Client -> Server routing stopped");
});
// Server -> Client
while !route_tcp(&mut client_send, &mut server_recv) {}
log("Server -> Client routing stopped");
while !route_tcp(&mut server_recv, &mut client_send) {}
client_send.shutdown(Shutdown::Both).unwrap();
println!("Server -> Client routing stopped");
});
}
Err(e) => {
log(&format!("Connection failed: {}", e));
println!("Connection failed: {}", e);
}
}
}
@@ -74,55 +65,49 @@ pub fn router() {
pub fn run() -> std::io::Result<()> {
let listener = TcpListener::bind("0.0.0.0:7878")?;
let mut connections: Vec<[u8; 6]> = Vec::new();
log("Gateway started on port 7878");
println!("Gateway started on port 7878");
std::thread::spawn(router);
for stream in listener.incoming() {
match stream {
Ok(mut stream) => {
log(&format!(
"New client connected from {}",
stream.peer_addr().unwrap()
));
println!("New client connected from {}", stream.peer_addr().unwrap());
let mut address = [0; 6];
let bytes_read = stream.read(&mut address)?;
if bytes_read == 0 {
log("Client disconnected before sending data.");
println!("Client disconnected before sending data.");
break;
}
log(&format!("Received address: {:?}", address));
println!("Received address: {:?}", address);
if let Some(con) = connections.last() {
log(&format!("Sending previous connection address: {:?}", con));
println!("Sending previous connection address: {:?}", con);
stream.write_all(con)?;
} else {
let default_addr = [0, 0, 0, 0, 0x1E, 0xC7];
log(&format!(
println!(
"No previous connections. Sending default address: {:?}",
default_addr
));
);
stream.write_all(&default_addr)?;
}
connections.push(address);
log(&format!(
println!(
"Stored new connection. Total connections: {}",
connections.len()
));
);
while stream.read(&mut []).unwrap() != 0 {}
log(&format!(
"Client {} disconnected",
stream.peer_addr().unwrap()
));
println!("Client {} disconnected", stream.peer_addr().unwrap());
stream.shutdown(Shutdown::Both).unwrap();
connections.remove(connections.iter().position(|v| v == &address).unwrap());
}
Err(e) => {
log(&format!("Connection failed: {}", e));
println!("Connection failed: {}", e);
}
}
}
+5 -1
View File
@@ -24,7 +24,11 @@ impl GhostStream {
}
pub fn write(&mut self, data: &[u8]) {
self.0.write_all(data).unwrap();
self.0.write_all(data).unwrap()
}
pub fn read(&mut self, data: &mut [u8]) -> usize {
self.0.read(data).unwrap()
}
}
+7
View File
@@ -4,5 +4,12 @@ fn main() {
if let Err(_) = ghostnet_rs::gateway::run() {
let mut stream = GhostStream::connect((0, 0, 0, 0), 7525);
stream.write("Hello, World".as_bytes());
let mut data = [0; 12];
let data_len = stream.read(&mut data);
if data_len == 0 {
return;
}
println!("From server: {}", String::from_utf8(data.to_vec()).unwrap());
}
}