I added threading (I don't really know what I'm doing)

The bytes update whenever a tracked file is edited/deleted.
This commit is contained in:
2025-11-28 23:50:38 +00:00
parent dfd6c9c370
commit ce643f2066
5 changed files with 139 additions and 204 deletions

View File

@@ -1,24 +1,67 @@
use std::
{
io,
fs,
io::{BufReader, prelude::*},
net::{TcpListener, TcpStream},
sync::mpsc,
thread,
path::PathBuf,
};
use lazy_static::lazy_static;
mod files;
lazy_static! {
static ref ROOT_DIR: PathBuf = fs::canonicalize(PathBuf::from("./root")).unwrap();
}
// TODO, remove .unwrap()
// TODO, make 'code' an enum
// TODO, safely modify bytes in thread.
// TODO, Makes paths more consistent.
// TODO, Avoid copying bytes
fn main() -> io::Result<()>
{
let bind_address: &str = "127.0.0.1:2025";
let index_file: &str = "index.npon";
let listener = TcpListener::bind(bind_address).unwrap();
println!("Listening at {}", bind_address);
let mut file_list: Vec<String> = vec![index_file.to_string()];
let (bytes, mut new_file_list) = files::read_file(index_file, 0);
// Default values
const BIND_ADDRESS: &str = "127.0.0.1:2008";
const INDEX_FILE: &str = "index.npon";
let (tx, rx) = mpsc::channel();
let listener = TcpListener::bind(BIND_ADDRESS).unwrap();
println!("Listening at {}", BIND_ADDRESS);
/*
let mut file_list: Vec<std::path::PathBuf> = vec![ROOT_DIR.join(INDEX_FILE)];
let (mut bytes, mut new_file_list) = files::read_file(INDEX_FILE, 0);
file_list.append(&mut new_file_list);
println!("Files encoded: {:?}", file_list);
*/
// File watch thread
thread::spawn(
move || {
let mut bytes: Vec<u8>;
let mut file_list: Vec<PathBuf>;
(bytes, file_list) = files::read_file(INDEX_FILE, 0);
file_list.push(ROOT_DIR.join(INDEX_FILE));
tx.send(bytes.clone()).unwrap();
'watch_loop: loop
{
let code = files::watch_files(&file_list);
if code == 0
{
println!("Re encoding index");
(bytes, file_list) = files::read_file(INDEX_FILE, 0);
file_list.push(ROOT_DIR.join(INDEX_FILE));
tx.send(bytes.clone()).unwrap();
}
}
}
);
for stream in listener.incoming() {
let bytes = rx.recv().unwrap();
let stream = stream.unwrap();
handle_connection(stream, &bytes);
}