client.example.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. const localtunnel_1 = __importDefault(require("../localtunnel"));
  7. const debug_1 = __importDefault(require("debug"));
  8. const debugLog = (0, debug_1.default)('tunnel:client');
  9. const port = process.env.PORT ? parseInt(process.env.PORT) : 23917;
  10. async function createTunnel() {
  11. debugLog('开始创建隧道, 端口: %d', port);
  12. try {
  13. debugLog('连接隧道服务器: %s', "https://23908.dev.d8dcloud.com");
  14. const tunnel = await (0, localtunnel_1.default)({
  15. port: port,
  16. host: "https://23908.dev.d8dcloud.com",
  17. });
  18. console.log(`隧道已创建: ${tunnel.url}`);
  19. debugLog('隧道创建成功, URL: %s', tunnel.url);
  20. // 添加事件监听
  21. tunnel.on("request", (info) => {
  22. console.log("隧道收到请求:", info);
  23. debugLog('处理请求: %o', info);
  24. });
  25. tunnel.on("error", (err) => {
  26. console.error("隧道错误:", err);
  27. debugLog('发生错误: %o', err);
  28. // 尝试重新连接
  29. debugLog('1秒后尝试重新连接...');
  30. setTimeout(createTunnel, 1000);
  31. });
  32. tunnel.on("close", () => {
  33. console.log("隧道关闭 - 尝试重新连接");
  34. debugLog('隧道关闭,1秒后尝试重新连接...');
  35. setTimeout(createTunnel, 1000);
  36. });
  37. // 添加进程退出处理
  38. process.on('SIGINT', () => {
  39. debugLog('收到退出信号,正在关闭隧道...');
  40. tunnel.close();
  41. process.exit(0);
  42. });
  43. return tunnel;
  44. }
  45. catch (err) {
  46. console.error("创建隧道失败:", err);
  47. debugLog('创建隧道失败: %o', err);
  48. debugLog('1秒后重试...');
  49. setTimeout(createTunnel, 1000);
  50. return null;
  51. }
  52. }
  53. // 启动隧道
  54. createTunnel().catch((err) => {
  55. console.error("启动失败:", err);
  56. debugLog('启动失败: %o', err);
  57. });
  58. // 添加未捕获异常处理
  59. process.on('uncaughtException', (err) => {
  60. console.error('未捕获的异常:', err);
  61. debugLog('未捕获的异常: %o', err);
  62. });
  63. process.on('unhandledRejection', (err) => {
  64. console.error('未处理的 Promise 拒绝:', err);
  65. debugLog('未处理的 Promise 拒绝: %o', err);
  66. });