Selaa lähdekoodia

Make it work with a single port

Johannes Zellner 7 kuukautta sitten
vanhempi
sitoutus
04a28ca7e8
2 muutettua tiedostoa jossa 63 lisäystä ja 59 poistoa
  1. 57 41
      server/index.mjs
  2. 6 18
      viewer/index.html

+ 57 - 41
server/index.mjs

@@ -26,7 +26,6 @@ function parseArgs(argv) {
     fps: 30,
     quality: 80,
     source: null,
-    httpPort: 8080,
     verbose: false,
   };
 
@@ -37,17 +36,15 @@ function parseArgs(argv) {
     else if (a === "--fps") out.fps = Number(argv[++i]);
     else if (a === "--quality") out.quality = Number(argv[++i]);
     else if (a === "--source") out.source = argv[++i];
-    else if (a === "--http-port") out.httpPort = Number(argv[++i]);
     else if (a === "--verbose" || a === "-v") out.verbose = true;
     else if (a === "--help" || a === "-h") {
       console.log(`Usage: node server/index.mjs [options]
 
-  --host ADDR       WebSocket bind (default 0.0.0.0)
-  --port N          WebSocket port (default 9000)
+  --host ADDR       HTTP + WebSocket bind (default 0.0.0.0)
+  --port N          Viewer (HTTP) and WebSocket on same port (default 9000)
   --fps N           Target framerate (default 30)
   --quality N       JPEG 1-100 (default 80)
   --source STR      Override GStreamer source element chain (before ! videoconvert)
-  --http-port N     Serve viewer over HTTP (default 8080; 0 to disable)
   --verbose         Extra portal + pipeline debug (also NEBUCAST_VERBOSE=1)
 
 Environment:
@@ -172,31 +169,51 @@ async function main() {
       shutdown(code !== 0 && code !== null ? 1 : 0);
     }
 
+    const viewerHtml = await readFile(VIEWER_PATH, "utf8");
+
     try {
-      wss = await new Promise((resolve, reject) => {
+      httpServer = createServer((req, res) => {
+        if (req.url === "/" || req.url?.startsWith("/index.html")) {
+          res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
+          res.end(viewerHtml);
+          return;
+        }
+        res.writeHead(404);
+        res.end();
+      });
+
+      wss = new WebSocketServer({
+        server: httpServer,
+        path: "/ws",
+        maxPayload: 4 * 1024 * 1024,
+        perMessageDeflate: false,
+      });
+      wss.on("connection", (ws) => {
+        clients.add(ws);
+        ws.on("close", () => clients.delete(ws));
+        ws.on("error", () => clients.delete(ws));
+      });
+
+      await new Promise((resolve, reject) => {
         let settled = false;
-        const server = new WebSocketServer({
-          host: opts.host,
-          port: opts.port,
-          maxPayload: 4 * 1024 * 1024,
-          perMessageDeflate: false,
-        });
-        server.once("listening", () => {
+        httpServer.once("listening", () => {
           if (settled) return;
           settled = true;
-          console.info("WebSocket stream: ws://%s:%d", opts.host, opts.port);
-          resolve(server);
+          console.info(
+            "Viewer: http://%s:%d/  |  WebSocket: ws://%s:%d/ws",
+            opts.host,
+            opts.port,
+            opts.host,
+            opts.port,
+          );
+          resolve(undefined);
         });
-        server.once("error", (err) => {
+        httpServer.once("error", (err) => {
           if (settled) return;
           settled = true;
           reject(err);
         });
-        server.on("connection", (ws) => {
-          clients.add(ws);
-          ws.on("close", () => clients.delete(ws));
-          ws.on("error", () => clients.delete(ws));
-        });
+        httpServer.listen(opts.port, opts.host);
       });
     } catch (err) {
       const code = err?.code;
@@ -206,9 +223,20 @@ async function main() {
           "[nebucast] Port %d is already in use. Use another port, e.g. npm start -- --port 9001",
           opts.port,
         );
-        console.error("[nebucast] See what holds it: ss -tlnp | grep ':%d '   or   fuser -v %d/tcp", opts.port, opts.port);
+        console.error(
+          "[nebucast] See what holds it: ss -tlnp | grep ':%d '   or   fuser -v %d/tcp",
+          opts.port,
+          opts.port,
+        );
+      }
+      const done = () => process.exit(1);
+      if (wss) {
+        wss.close(() => httpServer?.close(done) ?? done());
+      } else if (httpServer) {
+        httpServer.close(done);
+      } else {
+        done();
       }
-      process.exit(1);
     }
 
     wss.on("error", (err) => {
@@ -285,26 +313,10 @@ async function main() {
 
     if (!child) {
       cleanupResources();
-      wss.close(() => process.exit(1));
+      wss.close(() => httpServer.close(() => process.exit(1)));
       return;
     }
 
-    if (opts.httpPort > 0) {
-      const viewerHtml = await readFile(VIEWER_PATH, "utf8");
-      httpServer = createServer((req, res) => {
-        if (req.url === "/" || req.url?.startsWith("/index.html")) {
-          res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
-          res.end(viewerHtml);
-          return;
-        }
-        res.writeHead(404);
-        res.end();
-      });
-      httpServer.listen(opts.httpPort, opts.host, () => {
-        console.info("Viewer: http://%s:%d/", opts.host, opts.httpPort);
-      });
-    }
-
     process.off("SIGINT", onEarlySigint);
     process.once("SIGINT", () => shutdown(0));
     process.once("SIGTERM", () => shutdown(0));
@@ -313,7 +325,11 @@ async function main() {
     if (wss) {
       wss.close(() => {
         cleanupResources();
-        process.exit(1);
+        if (httpServer) {
+          httpServer.close(() => process.exit(1));
+        } else {
+          process.exit(1);
+        }
       });
     } else {
       cleanupResources();

+ 6 - 18
viewer/index.html

@@ -36,13 +36,6 @@
     padding:10px 20px;background:var(--surface);border-bottom:1px solid var(--border);
     flex-shrink:0;
   }
-  .controls label{font-size:13px;color:var(--text-dim)}
-  .controls input[type=text]{
-    background:var(--bg);border:1px solid var(--border);border-radius:6px;
-    color:var(--text);padding:6px 10px;font-size:13px;width:280px;
-    font-family:ui-monospace,monospace;
-  }
-  .controls input:focus{outline:none;border-color:var(--accent)}
   button{
     background:var(--accent);color:#fff;border:none;border-radius:6px;
     padding:6px 16px;font-size:13px;font-weight:500;cursor:pointer;
@@ -77,8 +70,6 @@
   </header>
 
   <div class="controls">
-    <label for="ws-url">Server</label>
-    <input type="text" id="ws-url" value="ws://localhost:9000">
     <button id="btn-connect">Connect</button>
   </div>
 
@@ -96,7 +87,6 @@
 <script>
 (function () {
   var frame      = document.getElementById("frame");
-  var urlInput   = document.getElementById("ws-url");
   var btnConn    = document.getElementById("btn-connect");
   var statusEl   = document.getElementById("status");
   var statusTxt  = document.getElementById("status-text");
@@ -118,12 +108,15 @@
     return (n / 1073741824).toFixed(1) + " GB";
   }
 
+  function wsUrlFromLocation() {
+    var scheme = location.protocol === "https:" ? "wss:" : "ws:";
+    return scheme + "//" + location.host + "/ws";
+  }
+
   function connect() {
-    var url = urlInput.value.trim();
-    if (!url) return;
     if (ws) disconnect();
 
-    ws = new WebSocket(url);
+    ws = new WebSocket(wsUrlFromLocation());
     ws.binaryType = "arraybuffer";
 
     ws.onopen = function () {
@@ -173,11 +166,6 @@
     if (ws && ws.readyState === WebSocket.OPEN) disconnect();
     else connect();
   });
-
-  if (location.hash.length > 1) {
-    urlInput.value = decodeURIComponent(location.hash.slice(1));
-    connect();
-  }
 })();
 </script>
 </body>