乐闻世界logo
搜索文章和话题

How does Tauri implement IPC communication between frontend and Rust backend

2月19日 19:24

Tauri's IPC (Inter-Process Communication) mechanism is the core for communication between the frontend and Rust backend, primarily implemented through the following methods:

Frontend Calling Rust Backend

Use the invoke method from @tauri-apps/api/tauri:

typescript
import { invoke } from '@tauri-apps/api/tauri'; // Call Rust command const result = await invoke('greet', { name: 'World' });

Defining Commands in Rust

Use the #[tauri::command] macro in src-tauri/src/main.rs:

rust
#[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}!", name) } fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![greet]) .run(tauri::generate_context!()) .expect("error while running tauri application"); }

Rust Backend Actively Pushing Messages to Frontend

Use the emit method:

rust
// Rust side window.emit("event-name", payload)?; // Frontend listening import { listen } from '@tauri-apps/api/event'; const unlisten = await listen('event-name', (event) => { console.log(event.payload); });

Data Serialization

  • Automatically uses JSON for serialization and deserialization
  • Supports complex data types (objects, arrays, etc.)
  • Rust side needs to implement Serialize and Deserialize traits

Error Handling

  • Rust side returning Result type is automatically converted to Promise
  • Frontend can use try-catch to catch errors
标签:Tauri