Tauri plugin

Example app

A Tauri app with a read-only client owned by Rust and a client of the webview.

examples/tauri-app: Rust registers a read-only core client and drives it, the webview attaches to it and connects its own chat client.

Run it

just servers-setup && just servers   # at the repository root: the Node test servers
cd crates/tauri-plugin-socketio/examples/tauri-app
pnpm install && pnpm tauri dev

The Rust side

src-tauri/src/main.rs
fn main() {
    tauri::Builder::default()
        .plugin(
            // the webview connects only to the test server; Rust's own clients are not limited
            tauri_plugin_socketio::Builder::new().allow_url_prefix(URL).build(),
        )
        .setup(|app| {
            // synchronous, before any await: no page script can connect("core") first
            app.socketio().reserve("core");
            let handle = app.handle().clone();
            tauri::async_runtime::spawn(async move {
                match core::start().await {
                    Ok(client) => {
                        if let Err(e) = handle.socketio().insert("core", client, Access::ReadOnly) {
                            eprintln!("core: {e}");
                        }
                    }
                    Err(e) => eprintln!("core: {e}"),
                }
            });
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

The webview

src/main.ts
import { attach, connect, SocketIoError } from 'tauri-plugin-socketio-api'

// A client Rust registered as read-only: observe it, emitting is refused.
let core
for (;;) {
  try {
    core = await attach('core', { events: ['tock'] })
    break
  } catch (e) {
    if (!(e instanceof SocketIoError && e.kind === 'UnknownClient')) throw e
    await new Promise((r) => setTimeout(r, 500))
  }
}
core.on('tock', (n, text) => console.log('tock', n, text))

// A client of this webview: connect, or after a reload take over the registered one.
const chat = await connect('chat', { url: URL, reconnectionDelay: 500 }).catch(async (e) => {
  if (e instanceof SocketIoError && e.kind === 'AlreadyExists') return attach('chat')
  throw e
})
chat.on('echo-back', (...args) => console.log('echo-back', ...args))