首页 > 解决方案 > TCP客户端在TCP客户端node.js中作为整体接收数据

问题描述

我将数据从 Arduino 服务器发送到我的 node.js 客户端,当我收到它时,我没有将它作为一个完整的字符串,而是作为字符,在我的控制台中我得到了这样的东西

收到:h 收到:e 收到:l 收到:l 收到:o

而不是收到
Received: 'hello'

请提供任何帮助

下面是我的 node.js 接收数据客户端和我的 Arduino 发送数据

client.on('data', function(data) {
    console.log('Received: ' + data);
});
 // listen for incoming clients
      EthernetClient clientA = serverA.available();
      if (clientA) {
          Serial.println("Client A connected.");

          while(clientA.available() > 0) {
              char dataA = clientA.read(); // 
              Serial.print(dataA);
              //clientA.write(dataA); // echo
              serverB.write(dataA); // forward
          }
      }

客户端 A 是另一个 node.js 客户端,将其发送到 Arduino 和 Arduino 重新发送数据。

标签: node.jsarduinotcpclient

解决方案


问题是您逐个字符地读取字符:

    char dataA = clientA.read(); // 
    Serial.print(dataA);

你可以做一个循环,将所有接收到的字符放入缓冲区,然后触发清空/打印缓冲区。一些伪代码 tpo 让你开始:

    char dataA;
    char buffer [32] = '\0'; // Buffer for 31 chars and the null terminator
    uint8_t i = 0;        
    while(clientA.available() > 0) {
          dataA = clientA.read();  
          buffer [i] = dataA; // we put the char into the buffer
         if (dataA != '/0') i++; // put the "pointer" to the next space in buffer
         else {               
          Serial.print(buffer);

         ... do something else with the buffer ....

          }
        }

阅读串行通信的概念并学习使用它们作为入门:
https ://www.oreilly.com/library/view/arduino-cookbook/9781449399368/ch04.html


推荐阅读