tcp.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 引入 Node.js 内置 net 模块(TCP 通信核心)
  2. const net = require("net");
  3. // 配置:服务器地址 + 端口
  4. const options = {
  5. host: "127.0.0.1", // 服务器IP
  6. port: 8052, // 服务器端口
  7. };
  8. // 创建 TCP 客户端
  9. const client = net.createConnection(options, () => {
  10. console.log("✅ TCP 连接成功!");
  11. // --------------------------
  12. // 需求1:连接成功 马上发送第一条消息
  13. // --------------------------
  14. client.write(`603`);
  15. });
  16. // 消息计数器(用于生成不同消息)
  17. let msgArr = [601, 602, 603];
  18. let msgIndex = 0;
  19. // --------------------------
  20. // 需求2:间隔 5 秒循环发送不同消息
  21. // --------------------------
  22. const intervalId = setInterval(() => {
  23. // 生成不同内容的消息
  24. const message = msgArr[msgIndex].toString(); // 转为字符串发送
  25. // 发送
  26. client.write(message);
  27. if (msgIndex >= msgArr.length - 1) msgIndex = 0;
  28. else msgIndex++;
  29. }, 5000); // 5000ms = 5秒
  30. // 监听服务器返回的数据
  31. client.on("data", (data) => {
  32. console.log("📥 服务器响应:", data.toString());
  33. });
  34. // 连接关闭
  35. client.on("close", () => {
  36. console.log("🔌 连接已关闭");
  37. clearInterval(intervalId); // 关闭定时器
  38. });
  39. // 错误处理
  40. client.on("error", (err) => {
  41. console.error("❌ 错误:", err.message);
  42. clearInterval(intervalId);
  43. });