tauri2项目在本地启动一个服务器,并支持控制停止还是启动

194 阅读1分钟

使用的是warp这个依赖库,这个依赖库是一个开源的rust server库,开源地址:github.com/seanmonstar…,使用起来也是非常的方便,只需要添加到自己本地cargo.toml依赖中,并跟上tokio这个依赖项。

tokio = { version = "1", features = ["full"] }
warp = "0.3"

然后在新创建两个函数,用于被前端调用:

mod command;
use std::sync::{Arc, Mutex};
mod utils;
use tauri::menu::*;

struct ServerState {
    server_handle: Option<tokio::task::JoinHandle<()>>,
}

#[tauri::command]
async fn start_server(
    state: tauri::State<'_, Arc<Mutex<ServerState>>>,
    path: String,
) -> Result<(), String> {
    println!("start_server: {}", path);
    let mut state = state.lock().unwrap();
    if state.server_handle.is_some() {
        return Err("Server is already running".into());
    }
    let path_clone = path.clone();
    let server_handle = tokio::spawn(async move {
        let route = warp::fs::dir(path_clone);
        warp::serve(route).run(([127, 0, 0, 1], 3030)).await;
    });
    state.server_handle = Some(server_handle);
    println!("Server started at http://127.0.0.1:3030");
    Ok(())
}

#[tauri::command]
async fn stop_server(state: tauri::State<'_, Arc<Mutex<ServerState>>>) -> Result<(), String> {
    let mut state = state.lock().unwrap();
    println!("stop_server");
    if let Some(handle) = state.server_handle.take() {
        handle.abort();
        Ok(())
    } else {
        Err("Server is not running".into())
    }
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]

再将server_handle添加到tauri中管理:

    tauri::Builder::default()
        .manage(Arc::new(Mutex::new(ServerState {
            server_handle: None,
        })))

并将启动和关闭两个函数添加到invoke_handler中:

然后在前端js中进行调用启动和关闭即可:

# selected是用户选择的一个文件夹路径
await invoke('start_server', { path: selected })
console.log('Server started successfully')

# 关闭
const stopServer = () => {
    invoke('stop_server')
}

最后就可以看到效果了: