diff --git a/src/App.tsx b/src/App.tsx index 8286a76..10804b5 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,12 +1,29 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import reactLogo from "./assets/react.svg"; import { invoke } from "@tauri-apps/api/core"; import "./App.css"; +import { EnclaveWebSocket } from "./protocol/ws"; function App() { const [greetMsg, setGreetMsg] = useState(""); const [name, setName] = useState(""); + useEffect(() => { + (async () => { + const ws = new EnclaveWebSocket("ws://localhost:3415"); + + ws.send({ + method: "Initialize", + public_key: "", + signature: "", + timestamp: 0, + hostname: "", + }); + + // console.log(await ws.read()); + })(); + }, []); + async function greet() { // Learn more about Tauri commands at https://tauri.app/develop/calling-rust/ setGreetMsg(await invoke("greet", { name })); diff --git a/src/protocol/ws.ts b/src/protocol/ws.ts index 2a4fa7e..153ecd3 100644 --- a/src/protocol/ws.ts +++ b/src/protocol/ws.ts @@ -2,33 +2,43 @@ import { ClientMethod, ServerMethod } from "./protocol"; export class EnclaveWebSocket { public websocket: WebSocket; - onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null; + onOpenQueue: Array<() => void>; public clientPublicKey: Uint8Array; public clientSecretKey: Uint8Array; - public serverPublicKey: Uint8Array; + public serverPublicKey?: Uint8Array; public constructor(url: string | URL) { - this.websocket = new WebSocket(url); this.clientPublicKey = new Uint8Array(); this.clientSecretKey = new Uint8Array(); + this.onOpenQueue = new Array(); - this.serverPublicKey = new Uint8Array(); - - this.onmessage = null; + this.websocket = new WebSocket(url); + this.websocket.onopen = () => { + this.onOpenQueue.forEach((fun) => fun()); + }; } - public send(method: ServerMethod) { + public async send(method: ServerMethod) { + if (this.websocket.readyState !== WebSocket.OPEN) { + return new Promise((ok) => { + this.onOpenQueue.push(() => { + this.websocket.send(JSON.stringify(method)); + ok(); + }); + }); + } + this.websocket.send(JSON.stringify(method)); } public async read(): Promise { return new Promise((ok) => { - this.onmessage = (msg) => { + this.websocket.onmessage = (msg) => { const data = JSON.parse(msg.data); ok(data); - this.onmessage = null; + this.websocket.onmessage = null; }; }); }