rustwebsockettauri

tauri + websocket client cant run together


Im trying to make an application that connects to a websocket server, the websocket server controls part of the application such as connect, etc. the issue is i cant seem to get the tauri app running along side the websocket client code its either the websocket works or the tauri works not both together, my current approach is to init tauri and the websocket client in different functions run_tauri_app and run_websocket_client the use tokio::join to run them together however this still doesn't work, in this instance the websocket client runs but the tauri doesn't work I'm guessing because tauri doesn't like that the event loop is running outside the main thread.

I need a pipeline connection between the tauri app and the websocket because the websocket client needs to access a app_handler, iv only ever used rust a couple time so this environment is a bit confusing to me so any pointers to how i may achieve this would be great.


use tauri::{
    CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
    WindowBuilder, WindowUrl, command
};

use futures_util::SinkExt;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};

use tokio::sync::mpsc;
use tokio::task;
use tokio_stream::StreamExt;

async fn run_websocket_client() {

    println!("websocket started");

    let url = "ws://localhost:2794";

    if let Ok((mut socket, _)) = connect_async(url).await {
        println!("Successfully connected to the WebSocket");
        
        // create message
        let message = Message::Text(
            r#"{
            "event": "authentication",
            "value": "key1"
          }"#
            .to_string()
                + "\n",
        );

        // send message
        if let Err(e) = socket.send(message).await {
            eprintln!("Error sending message: {:?}", e);
        }

        let (tx, mut rx) = mpsc::channel(100);

        // Spawn a new task to listen to the socket
        task::spawn(async move {
            while let Some(Ok(response)) = socket.next().await {
                println!("{response}");
                if tx.send(response).await.is_err() {
                    break;
                }
            }
        });

        // Main thread can do other work here
        while let Some(message) = rx.recv().await {
            // Process the message
        }
    } else {
        eprintln!("Failed to connect to the WebSocket");
    }
}

async fn run_tauri_app() {

    println!("tauri app started");
    
    let tray_menu = SystemTrayMenu::new()
        .add_item(CustomMenuItem::new("show", "Show"))
        .add_item(CustomMenuItem::new("hide", "Hide"))
        .add_native_item(SystemTrayMenuItem::Separator)
        .add_item(CustomMenuItem::new("quit", "Quit"));

    let system_tray = SystemTray::new().with_menu(tray_menu);

    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![get_data])
        .setup(|app| {
            
            // code removed however all it does is create a window for each monitor

            Ok(())
        })
        .system_tray(system_tray)
        .on_system_tray_event(|app, event| match event {
            SystemTrayEvent::MenuItemClick { id, .. } => {
                let window_labels = app.state::<Vec<String>>();
                for label in window_labels.iter() {
                    if let Some(window) = app.get_window(label) {
                        match id.as_str() {
                            "show" => {
                                window.show().unwrap();
                                window.set_focus().unwrap();
                            }
                            "hide" => {
                                window.hide().unwrap();
                            }
                            "quit" => {
                                app.exit(0);
                            }
                            _ => {}
                        }
                    }
                }
            }
            _ => {}
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");

}

#[tokio::main]
async fn main() {
    let websocket_task = tokio::spawn(run_websocket_client());
    let tauri_task = tokio::spawn(run_tauri_app());

    let _ = tokio::join!(tauri_task, websocket_task);
}

i made the websocket client the way it is simply because i don't know how to properly set it up, it works how i need it by sending an initial authentication message then receiving a success, etc. in the older version i setup a heartbeat system that needs to be added to the current code.

Iv had a look around and i cant really find anyone else that is doing what i need, I'm assuming there are projects out there that do the same since web sockets + desktop apps are pretty normal.


Solution

  • You need to let Tauri handle the Tokio runtime, and start your websocket client as part of your setup function:

    fn main() { // ← No async!
        tauri::Builder::default()
            .invoke_handler(tauri::generate_handler![get_data])
            .setup(|app| {
                tokio::spawn(run_websocket_client()); // ← Start the websocket client here
                Ok(())
            })
            .run(tauri::generate_context!())
            .expect("error while running tauri application");
    }
    

    See also: https://rfdonnelly.github.io/posts/tauri-async-rust-process/