recipe-sync-server-rs/src/main.rs

102 lines
2.0 KiB
Rust
Raw Normal View History

2026-02-21 01:55:41 +02:00
use std::{
fs,
2026-02-21 01:55:41 +02:00
io::Write,
net::{SocketAddr, TcpListener, TcpStream},
path::Path,
2026-02-21 01:55:41 +02:00
result,
str::FromStr,
};
use crate::buffer::ByteBuffer;
mod buffer;
2026-02-21 01:55:41 +02:00
const IP: &str = "0.0.0.0";
const PORT: &str = "9696";
type Result<T> = result::Result<T, ()>;
fn main() -> Result<()> {
let socket = SocketAddr::from_str(&format!("{}:{}", IP, PORT)).unwrap();
let listener = TcpListener::bind(socket).unwrap();
for stream in listener.incoming() {
match stream {
Ok(conn) => handle_connection(conn)?,
Err(e) => eprintln!("Something went wrong while listening {e}"),
}
}
Ok(())
}
fn handle_connection(mut conn: TcpStream) -> Result<()> {
let export = "./examples/";
2026-02-21 01:55:41 +02:00
let mut paths = vec![];
let mut buffer = ByteBuffer::default();
visit_dir(export, &mut paths);
buffer.write_usize(paths.len());
for file in paths {
let path = file.replace(export, "");
buffer.write_string(&path);
match fs::read(format!("./{file}")) {
2026-02-21 01:55:41 +02:00
Ok(data) => {
buffer.write_usize(data.len());
buffer.write_bytes(&data);
2026-02-21 01:55:41 +02:00
}
Err(_) => {
buffer.write_usize(0);
eprintln!("No file found")
}
2026-02-21 01:55:41 +02:00
};
}
let _ = conn.write_all(&buffer);
let _ = conn.flush();
2026-02-21 01:55:41 +02:00
Ok(())
}
fn visit_dir<P: AsRef<Path>>(path: P, file_paths: &mut Vec<String>) {
for entry in fs::read_dir(path).unwrap().flatten() {
if entry.path().is_dir() {
visit_dir(entry.path(), file_paths);
return;
}
let file_path = entry.path().to_str().unwrap().to_string();
file_paths.push(file_path);
}
}
2026-02-21 01:55:41 +02:00
#[cfg(test)]
mod tests {
use std::io::Read;
use super::*;
#[test]
fn test_connection() {
let conn = TcpStream::connect(format!("{}:{}", IP, PORT));
assert!(conn.is_ok());
let mut conn = conn.unwrap();
let mut buffer = ByteBuffer::default();
2026-02-21 01:55:41 +02:00
let bytes_read = conn.read_to_end(&mut buffer);
assert!(bytes_read.is_ok());
let file_name = buffer.read_string();
2026-02-21 01:55:41 +02:00
assert_eq!(file_name, "examples/test.md");
// let content = buffer.read_bytes(buffer.unread_len());
// println!("{}", String::from_utf8(content).unwrap());
2026-02-21 01:55:41 +02:00
}
}