😎 A custom invoke system for Tauri that leverages WebSockets

Overview

😎 tauri-awesome-rpc

This is a crate provides a custom invoke system for Tauri using a localhost JSON RPC WebSocket. Each message is delivered through Websocket using JSON RPC 2.0 specification.

With the advantage of using websocket, tauri-awesome-rpc also provides an event API. With AwesomeEmit you can emit event from the Rust backend and AwesomeEvent to listen to the event on the frontend.

Usage 🔧

First, add the dependency to your src-tauri/Cargo.toml file:

[dependencies]
tauri-awesome-rpc = { git = "https://github.com/ahkohd/tauri-awesome-rpc", branch = "dev" }

Then, setup the Websocket JSON RPC invoke system on the main.rs file:

use tauri::{Manager, Window, Wry};
use tauri_awesome_rpc::{AwesomeEmit, AwesomeRpc};
use serde_json::json;

fn main() {
  let awesome_rpc = AwesomeRpc::new(vec!["tauri://localhost", "http://localhost:*"]);

  tauri::Builder::default()
    .invoke_system(awesome_rpc.initialization_script(), AwesomeRpc::responder())
    .setup(move |app| {
      awesome_rpc.start(app.handle());
      Ok(())
    })
    .invoke_handler(tauri::generate_handler![my_command, report_time_elapsed])
    .run(tauri::generate_context!())
    .expect("error while running tauri application")
}

#[tauri::command]
fn my_command(args: u64) -> Result<String, ()> {
  println!("executed command with args {:?}", args);

  Ok("executed".into())
}

#[tauri::command]
fn report_time_elapsed(window: Window<Wry>) {
  tauri::async_runtime::spawn(async move {
    let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(250));
    let start_time = std::time::Instant::now();

    loop {
      interval.tick().await;

      // emit an awesome event to the main window
      window
        .state::<AwesomeEmit>()
        .emit("main", "time_elapsed", json!(start_time.elapsed()));
    }
  });
}

Then, on the frontend:

  • Use your Tauri invoke method as usual.
  • Use window.AwesomeEvent to listen to the events emitted using AwesomeEmit from the Rust backend.
<html>
  <body>
    <div>
      <h1>tauri-awesome-rpc</h1>

      <h5>invoke test</h5>
      <div id="response"></div>

      <h5>AwesomeEvent.listen test</h5>
      <div id="time_elapsed"></div>
    </div>

    <script>
      const response = document.getElementById("response");
      const timeElapsed = document.getElementById("time_elapsed");

      window.__TAURI__
        .invoke("my_command", { args: 5 })
        .then((data) => {
          response.innerText = data;
        })
        .catch((error) => {
          console.log(error, "error");
          response.innerText = error;
        });

      window.__TAURI__.invoke("report_time_elapsed");

      let _unsubscribe = window.AwesomeEvent.listen("time_elapsed", (data) => {
        timeElapsed.innerText = JSON.stringify(data);
      });
    </script>
  </body>
</html>

TypeScript 🔥

Add the following type definition to your project's global.d.ts file:

interface Window {
  AwesomeEvent: {
    listen(eventName: string, callback: (data) => void): () => void;
  };
}
You might also like...
Dynamically invoke arbitrary unmanaged code.

DInvoke_rs Rust port of Dinvoke. DInvoke_rs may be used for many purposes such as PE parsing, dynamic exported functions resolution, dynamically loadi

Rust port of the official Windows Driver Samples on Github. Leverages windows-drivers-rs

Rust Driver Samples This is a Rust port of the driver samples from the original Windows Driver Samples on Github. The repository provides examples and

Decode SCALE bytes into custom types using a scale-info type registry and a custom Visitor impl.

scale-decode This crate attempts to simplify the process of decoding SCALE encoded bytes into a custom data structure given a type registry (from scal

Catch Tailwindcss Errors  at Compile-Time Before They Catch You, without making any change to your code!  Supports overriding, extending, custom classes, custom modifiers, Plugins and many more 🚀🔥🦀
Catch Tailwindcss Errors at Compile-Time Before They Catch You, without making any change to your code! Supports overriding, extending, custom classes, custom modifiers, Plugins and many more 🚀🔥🦀

twust Twust is a powerful static checker in rust for TailwindCSS class names at compile-time. Table of Contents Overview Installation Usage Statement

Lightweight, event-driven WebSockets for Rust.

WS-RS Lightweight, event-driven WebSockets for Rust. /// A WebSocket echo server listen("127.0.0.1:3012", |out| { move |msg| { out.send(ms

Command-line client for WebSockets, like netcat (or curl) for ws:// with advanced socat-like functions

websocat Netcat, curl and socat for WebSockets. Examples Connect to public echo server $ websocat ws://echo.websocket.org 123 123 ABC ABC Serve and c

Synchronized state machines for Rust over WebSockets.

Aper is a framework for real-time sharing of application state over WebSockets.

Autogenerated async RPC bindings that instantly connect a JS frontend to a Rust backend service via WebSockets and WASM.

Turbocharger Autogenerated async RPC bindings that instantly connect a JS frontend to a Rust backend service via WebSockets and WASM. See https://gith

Rust + wasm + websockets

This is a template repo for eframe, a framework for writing apps using egui.

Clearly a repo about websockets and their comparison...

Tags Go vs Typescript: Video 1 of the series is tag go-vs-ts-video-1 Current Project Video 2 and 3 are going to be likely Go vs Rust vs Typescript, bu

Composable WebSockets made easy, for Rust 🦀

ezsockets Have you ever struggle with creating a WebSocket server or a client in Rust? This crate is for you. High level abstraction of WebSocket, han

Plutonium is a two-device chat application that utilises WebSockets and a X25519 ECDH Key Exchange

Plutonium is a two-device chat application that utilises WebSockets and a X25519 ECDH Key Exchange, in addition to AES-256 to securely communicate between the two clients.

Rust API connector for Bybit's WebSockets APIs.

rust-bybit English | 简体中文 Unofficial Rust API connector for Bybit's WebSockets APIs. Disclaimer This is an unofficial Rust API connector for Bybit's A

A simple web server(and library) to display server stats over HTTP and Websockets/SSE or stream it to other systems.

x-server-stats A simple web server(and library) to display server stats over HTTP and Websockets/SSE or stream it to other systems. x-server(in x-serv

A MITM Proxy Written in Rust 🦀! Toolkit for HTTP/1, HTTP/2, and WebSockets with SSL/TLS Capabilities. Learning Project.
A MITM Proxy Written in Rust 🦀! Toolkit for HTTP/1, HTTP/2, and WebSockets with SSL/TLS Capabilities. Learning Project.

Man In The Middle Proxy Description Rust-based Man in the Middle proxy, an early-stage project aimed at providing visibility into network traffic. Cur

A command-line tool for exposing a wrapped program's standard IO using WebSockets/SSE
A command-line tool for exposing a wrapped program's standard IO using WebSockets/SSE

cmdpiped cmdpiped is a command-line tool for exposing a wrapped cli program's standard IO to WebSockets/SSE Installation Ready to use Binaries are ava

Fork of the Official Python3 API connector for Bybit's HTTP (bybit) and WebSockets APIs to rust

Fork of pybit python libary in Rust For the rust lovers and creators for bybit exchange version 5 Official Python3 API connector for Bybit's HTTP and

An efficient pictures manager based on custom tags and file system organization.

PicturesManager An efficient pictures manager based on custom tags and file system organization. Developed with Tauri (web app) with a Rust backend an

⚙️ Workshop Publishing Utility for Garry's Mod, written in Rust & Svelte and powered by Tauri
⚙️ Workshop Publishing Utility for Garry's Mod, written in Rust & Svelte and powered by Tauri

⚙️ gmpublisher Currently in Beta development. A powerful and feature-packed Workshop publisher for Garry's Mod is finally here! Click for downloads Ar

Comments
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • Cargo.toml (cargo)
    • .github/workflows/audit.yml (github-actions)
    • .github/workflows/covector-status.yml (github-actions)
    • .github/workflows/covector-version-or-publish.yml (github-actions)
    • .github/workflows/format.yml (github-actions)
    • .github/workflows/lint.yml (github-actions)
    • .github/workflows/test.yml (github-actions)

    Configuration

    🔡 Renovate has detected a custom config for this PR. Feel free to ask for help if you have any doubts and would like it reviewed.

    Important: Now that this branch is edited, Renovate can't rebase it from the base branch any more. If you make changes to the base branch that could impact this onboarding PR, please merge them manually.

    What to Expect

    With your current configuration, Renovate will create 6 Pull Requests:

    chore(deps): update tauri-apps/create-pull-request action to v2.8.1
    fix(deps): update rust crate tauri to 1.2.0
    • Schedule: ["at any time"]
    • Branch name: renovate/tauri-monorepo
    • Merge into: dev
    • Upgrade tauri to 1.2.0
    chore(deps): update actions/cache action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-cache-3.x
    • Merge into: dev
    • Upgrade actions/cache to v3
    chore(deps): update actions/checkout action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-checkout-3.x
    • Merge into: dev
    • Upgrade actions/checkout to v3
    chore(deps): update actions/setup-node action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-setup-node-3.x
    • Merge into: dev
    • Upgrade actions/setup-node to v3
    chore(deps): update tauri-apps/create-pull-request action to v3

    🚸 Branch creation will be limited to maximum 2 per hour, so it doesn't swamp any CI resources or spam the project. See docs for prhourlylimit for details.


    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
Owner
Victor Aremu
Software Engineer
Victor Aremu
Command-line client for WebSockets, like netcat (or curl) for ws:// with advanced socat-like functions

websocat Netcat, curl and socat for WebSockets. Examples Connect to public echo server $ websocat ws://echo.websocket.org 123 123 ABC ABC Serve and c

Vitaly Shukela 5k Jan 4, 2023
Synchronized state machines for Rust over WebSockets.

Aper is a framework for real-time sharing of application state over WebSockets.

null 191 Dec 20, 2022
Rust + wasm + websockets

This is a template repo for eframe, a framework for writing apps using egui.

Emil Ernerfeldt 12 Oct 3, 2022
Clearly a repo about websockets and their comparison...

Tags Go vs Typescript: Video 1 of the series is tag go-vs-ts-video-1 Current Project Video 2 and 3 are going to be likely Go vs Rust vs Typescript, bu

ThePrimeagen 344 Dec 31, 2022
Composable WebSockets made easy, for Rust 🦀

ezsockets Have you ever struggle with creating a WebSocket server or a client in Rust? This crate is for you. High level abstraction of WebSocket, han

Grzegorz Baranski 55 Dec 30, 2022
Rust API connector for Bybit's WebSockets APIs.

rust-bybit English | 简体中文 Unofficial Rust API connector for Bybit's WebSockets APIs. Disclaimer This is an unofficial Rust API connector for Bybit's A

yufuquant 12 Nov 12, 2022
A MITM Proxy Written in Rust 🦀! Toolkit for HTTP/1, HTTP/2, and WebSockets with SSL/TLS Capabilities. Learning Project.

Man In The Middle Proxy Description Rust-based Man in the Middle proxy, an early-stage project aimed at providing visibility into network traffic. Cur

null 158 Mar 9, 2023
A command-line tool for exposing a wrapped program's standard IO using WebSockets/SSE

cmdpiped cmdpiped is a command-line tool for exposing a wrapped cli program's standard IO to WebSockets/SSE Installation Ready to use Binaries are ava

Geoffrey Mureithi 10 Nov 11, 2022
A custom invoke system for Tauri that leverages a localhost server

Tauri Invoke HTTP This is a crate that provides a custom invoke system for Tauri using a localhost server. Each message is delivered through a XMLHttp

Tauri 17 Dec 17, 2022
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 294 Dec 23, 2022