I'm looking at building a ui that starts/stops a http server using tauri.
I'm using this guide Calling Rust from the frontend | Tauri Apps
I'm new to rust, this code does not work, but it sort of shows what im trying to achieve
pub struct ServerThread {
server_thread: JoinHandle<T>
}
enum Message {
Terminate,
}
impl ServerThread {
pub fn create(port: i16) -> ServerThread {
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let server_thread = thread::spawn(move || {
/// start the server
setup_http_server(port);
loop {
let message = receiver.lock().unwrap().recv().unwrap();
match message {
Message::Terminate => {
println!("Worker was told to terminate." );
},
}
}
});
Self {
server_thread
}
}
pub fn stop(&self) -> Result<(), String> {
Ok(())
}
}
fn setup_http_server(port: i16) -> Result<(), String> {
let listener = TcpListener::bind("127.0.0.1:".to_owned() + &*port.to_string()).unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
println!("Connection established!");
}
Ok(())
}
Using Tauri you can pass commands back from the react frontend
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
server::instance::startServer,
server::instance::stopServer,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
The generate handler allows you to pass in functions and params. The issue is, i have no idea to pass the same reference of the impl ServerThread and call the terminate message
#[tauri::command]
pub fn startServer(port: i16) -> Result<(), String> {
let server_thread = ServerThread::create(port);
Ok(())
}
#[tauri::command]
pub fn stopServer() -> Result<(), String> {
let server_thread = ServerThread::stop();
Ok(())
}
the stop command doesn't work as it asks me to pass "self" when i try ServerThread.stop(); it doesn't have the properties to access the server thread and shut it down
Hoping you guys might have some advice as i seem to hit a roadblock can't find the docs that explain how to solve this.