| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- // 引入 Node.js 内置 net 模块(TCP 通信核心)
- const net = require("net");
- // 配置:服务器地址 + 端口
- const options = {
- host: "127.0.0.1", // 服务器IP
- port: 8052, // 服务器端口
- };
- // 创建 TCP 客户端
- const client = net.createConnection(options, () => {
- console.log("✅ TCP 连接成功!");
- // --------------------------
- // 需求1:连接成功 马上发送第一条消息
- // --------------------------
- client.write(`603`);
- });
- // 消息计数器(用于生成不同消息)
- let msgArr = [601, 602, 603];
- let msgIndex = 0;
- // --------------------------
- // 需求2:间隔 5 秒循环发送不同消息
- // --------------------------
- const intervalId = setInterval(() => {
- // 生成不同内容的消息
- const message = msgArr[msgIndex].toString(); // 转为字符串发送
- // 发送
- 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);
- });
|