From 8751ba26ebf7b7761b9e237f2bf3453623dd1018 Mon Sep 17 00:00:00 2001 From: polwex Date: Mon, 6 Oct 2025 10:13:39 +0700 Subject: added frontend WS connection for demonstration purposes --- gui/src/components/WsWidget.tsx | 123 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 gui/src/components/WsWidget.tsx (limited to 'gui/src/components/WsWidget.tsx') diff --git a/gui/src/components/WsWidget.tsx b/gui/src/components/WsWidget.tsx new file mode 100644 index 0000000..75c773d --- /dev/null +++ b/gui/src/components/WsWidget.tsx @@ -0,0 +1,123 @@ +import { useWebSocket } from "@/hooks/useWs"; +import { useState } from "react"; + +type WidgetProps = { + url: string; + protocols?: string | string[]; +}; + +export default function WebSocketWidget({ url, protocols }: WidgetProps) { + const { + status, + retryCount, + lastMessage, + error, + bufferedAmount, + send, + reconnectNow, + close, + } = useWebSocket({ + url, + protocols, + onMessage: (ev) => { + // Example: auto reply to pings + console.log(ev.data, "ws event"); + if ( + typeof ev.data === "string" && + // ev.data.toLowerCase().includes("ping") + ev.data.toLowerCase().trim() == "ping" + ) { + try { + console.log("sending pong"); + send("pong"); + } catch {} + } + }, + }); + + const [outbound, setOutbound] = useState(""); + + return ( +
+
+

WebSocketWidget

+ + {status.toUpperCase()} {retryCount ? `(retry ${retryCount})` : ""} + +
+ +
+
+ URL: {url} +
+
+ Buffered: {bufferedAmount} bytes +
+ {error && ( +
+ Error:{" "} + {"message" in error + ? (error as any).message + : String(error.type || "error")} +
+ )} +
+ +
+
Last message:
+
+ {lastMessage + ? typeof lastMessage.data === "string" + ? lastMessage.data + : "(binary)" + : "—"} +
+
+ +
{ + e.preventDefault(); + if (!outbound) return; + send(outbound); + setOutbound(""); + }} + > + setOutbound(e.target.value)} + /> + +
+ +
+ + +
+ +
+ Usage +
+          {`import WebSocketWidget from "./WebSocketWidget";
+
+export default function App() {
+  return (
+    
+ +
+ ); +} +`} +
+
+
+ ); +} -- cgit v1.2.3