Przeglądaj źródła

mod:新增http服务,暂时未用到,代码暂留

panqiuyao 8 miesięcy temu
rodzic
commit
fb46e2c34c
2 zmienionych plików z 77 dodań i 3 usunięć
  1. 9 3
      electron/index.js
  2. 68 0
      electron/server/http.js

+ 9 - 3
electron/index.js

@@ -1,10 +1,12 @@
 const { Application } = require('ee-core');
+const HttpServer = require('./server/http');
 
 class Index extends Application {
 
   constructor() {
     super();
     // this === eeApp;
+    this.httpServer = new HttpServer();
   }
 
   /**
@@ -35,16 +37,20 @@ class Index extends Application {
         win.focus();
       })
     }
+
+    // 启动HTTP服务
+  //  this.httpServer.start();
   }
 
   /**
    * before app close
-   */  
+   */
   async beforeClose () {
     // do some things
-
+    // 关闭HTTP服务器
+  //  this.httpServer.stop();
   }
 }
 
 Index.toString = () => '[class Index]';
-module.exports = Index;
+module.exports = Index;

+ 68 - 0
electron/server/http.js

@@ -0,0 +1,68 @@
+const http = require('http');
+const fs = require('fs');
+const path = require('path');
+
+//mod:新增http服务,暂时未用到,代码暂留
+class HttpServer {
+  constructor() {
+    this.server = null;
+  }
+
+  start() {
+
+    const staticDir =  path.join(__dirname, '../config'); // 从config文件中读取静态资源目录,默认为public目录
+
+    this.server = http.createServer((req, res) => {
+      let filePath = path.join(staticDir, req.url === '/' ? 'index.html' : req.url);
+      const extname = String(path.extname(filePath)).toLowerCase();
+      const mimeTypes = {
+        '.html': 'text/html',
+        '.js': 'text/javascript',
+        '.css': 'text/css',
+        '.json': 'application/json',
+        '.png': 'image/png',
+        '.jpg': 'image/jpg',
+        '.gif': 'image/gif',
+        '.wav': 'audio/wav',
+        '.mp4': 'video/mp4',
+        '.woff': 'application/font-woff',
+        '.ttf': 'application/font-ttf',
+        '.eot': 'application/vnd.ms-fontobject',
+        '.otf': 'application/font-otf',
+        '.svg': 'application/image/svg+xml'
+      };
+
+      const contentType = mimeTypes[extname] || 'application/octet-stream';
+
+      fs.readFile(filePath, (error, content) => {
+        if (error) {
+          if (error.code === 'ENOENT') {
+            res.writeHead(404);
+            res.end('404 Not Found');
+          } else {
+            res.writeHead(500);
+            res.end(`Server Error: ${error.code}`);
+          }
+        } else {
+          res.writeHead(200, { 'Content-Type': contentType });
+          res.end(content, 'utf-8');
+        }
+      });
+    });
+
+    const port = 7072; // 从config文件中读取端口号,默认为7072
+    this.server.listen(port, () => {
+      console.log(`HTTP Server running at http://localhost:${port}/`);
+    });
+  }
+
+  stop() {
+    if (this.server) {
+      this.server.close(() => {
+        console.log('HTTP Server closed');
+      });
+    }
+  }
+}
+
+module.exports = HttpServer;