server.exsample.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. const http = require("http");
  2. const debug = require("debug")("localtunnel:client");
  3. // 直接引用本地源码而不是 npm 包
  4. const localtunnel = require("./localtunnel");
  5. const server = http.createServer((req, res) => {
  6. console.log(`收到请求: ${req.method} ${req.url}`); // 添加请求日志
  7. res.statusCode = 200;
  8. res.setHeader("Content-Type", "text/plain");
  9. res.end("Hello, World!");
  10. });
  11. const port = 23906;
  12. async function createTunnel() {
  13. try {
  14. debug('开始创建隧道...');
  15. const tunnel = await localtunnel({
  16. port: port,
  17. host: 'https://pre.d8d.fun',
  18. // host: "https://23905.dev.d8dcloud.com",
  19. // subdomain: 'simple-js-line-f9s-gudz'
  20. });
  21. console.log(`隧道已创建: ${tunnel.url}`);
  22. // 添加更详细的事件监听
  23. tunnel.on("request", (info) => {
  24. debug('隧道请求:', info);
  25. });
  26. tunnel.on("error", (err) => {
  27. debug('隧道错误:', err.stack || err);
  28. setTimeout(createTunnel, 1000);
  29. });
  30. tunnel.on("close", () => {
  31. debug('隧道关闭事件触发');
  32. setTimeout(createTunnel, 1000);
  33. });
  34. // 监听更多事件
  35. tunnel.on("connect", () => {
  36. debug('隧道连接成功');
  37. });
  38. tunnel.on('disconnect', () => {
  39. debug('隧道断开连接');
  40. });
  41. // 监听底层socket事件
  42. if (tunnel.tunnelCluster) {
  43. debug('开始监听隧道集群事件');
  44. tunnel.tunnelCluster.on('error', (err) => {
  45. debug('隧道集群错误:', err.stack || err);
  46. });
  47. tunnel.tunnelCluster.on('dead', () => {
  48. debug('隧道集群死亡');
  49. });
  50. }
  51. // 定期检查隧道状态
  52. const healthCheck = setInterval(() => {
  53. if (tunnel.closed) {
  54. debug('健康检查: 隧道已关闭');
  55. clearInterval(healthCheck);
  56. } else {
  57. debug('健康检查: 隧道正常');
  58. }
  59. }, 5000);
  60. return tunnel;
  61. } catch (err) {
  62. debug('创建隧道失败:', err.stack || err);
  63. setTimeout(createTunnel, 1000);
  64. }
  65. }
  66. // 启动 HTTP 服务器
  67. server.listen(port, async () => {
  68. debug(`本地服务器启动在端口 ${port}`);
  69. let tunnel = await createTunnel();
  70. debug('隧道实例创建完成');
  71. // 监控隧道状态
  72. setInterval(() => {
  73. if (tunnel && !tunnel.closed) {
  74. debug('隧道状态: 活跃');
  75. } else {
  76. debug('隧道状态: 已关闭');
  77. }
  78. }, 10000);
  79. // 优雅退出
  80. process.on("SIGINT", () => {
  81. debug('收到退出信号');
  82. if (tunnel) {
  83. tunnel.close();
  84. debug('隧道已主动关闭');
  85. }
  86. server.close(() => {
  87. debug('服务器已关闭');
  88. process.exit(0);
  89. });
  90. });
  91. });
  92. // 全局错误处理
  93. process.on('uncaughtException', (err) => {
  94. debug('未捕获的异常:', err.stack || err);
  95. });
  96. process.on('unhandledRejection', (err) => {
  97. debug('未处理的 Promise 拒绝:', err.stack || err);
  98. });