const http = require("http"); const debug = require("debug")("localtunnel:client"); // 直接引用本地源码而不是 npm 包 const localtunnel = require("./localtunnel"); const server = http.createServer((req, res) => { console.log(`收到请求: ${req.method} ${req.url}`); // 添加请求日志 res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.end("Hello, World!"); }); const port = 23906; async function createTunnel() { try { debug('开始创建隧道...'); const tunnel = await localtunnel({ port: port, host: 'https://pre.d8d.fun', // host: "https://23905.dev.d8dcloud.com", // subdomain: 'simple-js-line-f9s-gudz' }); console.log(`隧道已创建: ${tunnel.url}`); // 添加更详细的事件监听 tunnel.on("request", (info) => { debug('隧道请求:', info); }); tunnel.on("error", (err) => { debug('隧道错误:', err.stack || err); setTimeout(createTunnel, 1000); }); tunnel.on("close", () => { debug('隧道关闭事件触发'); setTimeout(createTunnel, 1000); }); // 监听更多事件 tunnel.on("connect", () => { debug('隧道连接成功'); }); tunnel.on('disconnect', () => { debug('隧道断开连接'); }); // 监听底层socket事件 if (tunnel.tunnelCluster) { debug('开始监听隧道集群事件'); tunnel.tunnelCluster.on('error', (err) => { debug('隧道集群错误:', err.stack || err); }); tunnel.tunnelCluster.on('dead', () => { debug('隧道集群死亡'); }); } // 定期检查隧道状态 const healthCheck = setInterval(() => { if (tunnel.closed) { debug('健康检查: 隧道已关闭'); clearInterval(healthCheck); } else { debug('健康检查: 隧道正常'); } }, 5000); return tunnel; } catch (err) { debug('创建隧道失败:', err.stack || err); setTimeout(createTunnel, 1000); } } // 启动 HTTP 服务器 server.listen(port, async () => { debug(`本地服务器启动在端口 ${port}`); let tunnel = await createTunnel(); debug('隧道实例创建完成'); // 监控隧道状态 setInterval(() => { if (tunnel && !tunnel.closed) { debug('隧道状态: 活跃'); } else { debug('隧道状态: 已关闭'); } }, 10000); // 优雅退出 process.on("SIGINT", () => { debug('收到退出信号'); if (tunnel) { tunnel.close(); debug('隧道已主动关闭'); } server.close(() => { debug('服务器已关闭'); process.exit(0); }); }); }); // 全局错误处理 process.on('uncaughtException', (err) => { debug('未捕获的异常:', err.stack || err); }); process.on('unhandledRejection', (err) => { debug('未处理的 Promise 拒绝:', err.stack || err); });