// 引入 Node.js 内置 net 模块(TCP 通信核心) const net = require("net"); // "CMD=501" // 101:空中成像 开 // 102:空中成像 关 // 201:文物互动墙 开 // 202:文物互动墙 关 // 301:透明展示柜A 开 // 302:透明展示柜A 关 // 401:透明展示柜B 开 // 402:透明展示柜B 关 // 501:AI数字人 开 // 502:AI数字人 关 // 601:所有设备全部 开 // 602:所有设备全部 关 // 配置:服务器地址 + 端口 const options = { host: "127.0.0.1", // 服务器IP port: 8080, // 服务器端口 }; // 创建 TCP 客户端 const client = net.createConnection(options, () => { console.log("✅ TCP 连接成功!"); // -------------------------- // 需求1:连接成功 马上发送第一条消息 // -------------------------- client.write(`CMD=601`); }); // 消息计数器(用于生成不同消息) let msgArr = [102, 202, 302, 402, 502, 101, 201, 301, 401, 501, 602, 601]; let msgIndex = 0; // -------------------------- // 需求2:间隔 5 秒循环发送不同消息 // -------------------------- const intervalId = setInterval(() => { // 生成不同内容的消息 const message = `CMD=${msgArr[msgIndex]}`; // 发送 client.write(message); if (msgIndex >= msgArr.length - 1) msgIndex = 0; else msgIndex++; }, 5000); // 5000ms = 5秒 // 监听服务器返回的数据 client.on("data", (data) => { console.log("📥 服务器响应:", data.toString()); }); // 连接关闭 client.on("close", () => { console.log("🔌 连接已关闭"); clearInterval(intervalId); // 关闭定时器 }); // 错误处理 client.on("error", (err) => { console.error("❌ 错误:", err.message); clearInterval(intervalId); });