()
| 7 | |
| 8 | // Initialize persistent WebSocket connection |
| 9 | function initWebSocket() { |
| 10 | // Prevent multiple simultaneous connection attempts |
| 11 | if (isConnecting || globalWS) { |
| 12 | return; // Already connecting or a connection exists |
| 13 | } |
| 14 | |
| 15 | isConnecting = true; |
| 16 | |
| 17 | var protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; |
| 18 | var url = protocol + "//" + window.location.hostname + ":" + window.location.port + "/data/?Token=" + getCookie("Token"); |
| 19 | |
| 20 | globalWS = new WebSocket(url); |
| 21 | |
| 22 | globalWS.onopen = function () { |
| 23 | isConnecting = false; |
| 24 | WS_AVAILABLE = true; |
| 25 | SERVER_CONNECTION = false; |
| 26 | console.log("WebSocket connected"); |
| 27 | |
| 28 | // Send any pending requests |
| 29 | while (pendingRequests.length > 0) { |
| 30 | const request = pendingRequests.shift(); |
| 31 | if (request) { |
| 32 | if (globalWS.readyState === WebSocket.OPEN) { |
| 33 | globalWS.send(JSON.stringify(request)); |
| 34 | } else { |
| 35 | // Put it back in the queue if not ready |
| 36 | pendingRequests.unshift(request); |
| 37 | break; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // Automatically send updateLog to get server data and create menu |
| 43 | setTimeout(() => { |
| 44 | if (globalWS && globalWS.readyState === WebSocket.OPEN) { |
| 45 | |
| 46 | const updateLogData = { cmd: "updateLog" }; |
| 47 | globalWS.send(JSON.stringify(updateLogData)); |
| 48 | } |
| 49 | }, 100); // Small delay to ensure connection is fully ready |
| 50 | }; |
| 51 | |
| 52 | globalWS.onerror = function (e) { |
| 53 | console.log("WebSocket error:", e); |
| 54 | SERVER_CONNECTION = false; |
| 55 | WS_AVAILABLE = false; |
| 56 | // Don't close the connection on error - let it try to recover |
| 57 | }; |
| 58 | |
| 59 | globalWS.onclose = function () { |
| 60 | isConnecting = false; |
| 61 | WS_AVAILABLE = false; |
| 62 | SERVER_CONNECTION = false; |
| 63 | console.log("WebSocket disconnected"); |
| 64 | |
| 65 | // Clear the globalWS reference |
| 66 | globalWS = null; |
no test coverage detected