feat: implement websocket realtime data streaming
This commit is contained in:
@@ -33,4 +33,47 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
updateUptime();
|
||||
// Update every second
|
||||
setInterval(updateUptime, 1000);
|
||||
|
||||
// WebSocket Connection
|
||||
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsUrl = `${protocol}//${window.location.host}/ws`;
|
||||
|
||||
function connectWs() {
|
||||
const ws = new WebSocket(wsUrl);
|
||||
const statusIndicator = document.querySelector(".status-indicator");
|
||||
|
||||
ws.onopen = () => {
|
||||
console.log("WS Connected");
|
||||
if (statusIndicator) statusIndicator.classList.add("online");
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.type === "HEARTBEAT") {
|
||||
console.log("Heartbeat:", msg.data);
|
||||
// Sync uptime?
|
||||
// We can optionally verify if client clock is drifting, but let's keep it simple.
|
||||
} else if (msg.type === "WELCOME") {
|
||||
console.log(msg.message);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("WS Parse Error", e);
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
console.log("WS Disconnected");
|
||||
if (statusIndicator) statusIndicator.classList.remove("online");
|
||||
// Retry in 5s
|
||||
setTimeout(connectWs, 5000);
|
||||
};
|
||||
|
||||
ws.onerror = (err) => {
|
||||
console.error("WS Error", err);
|
||||
ws.close();
|
||||
};
|
||||
}
|
||||
|
||||
connectWs();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user