TCP客户端无法从Arduino以太网服务器接收所有数据

时间:2018-01-09 14:28:56

标签: c# arduino

我想将一些数据从Arduino服务器发送到C#应用程序并在文本框中显示。但是当我尝试从C#中读取数据时,我只获得了第一行发送的数据。

这是Arduino的侧码:

IPAddress ip(192, 168, 1, 85);
EthernetServer server(64000);
Ethernet.begin(mac, ip);
server.begin();

void setup() {
 Serial.begin(9600);
}

void loop() {
if(EthernetClient client = server.available()){
  client.println("data1"); //I only get this line in C#
  client.println("data2");
  client.println("data3");
  client.println("data4");
  client.println("data5");
  client.stop();
 }
}

我认为我的C#端代码肯定存在一些问题。

C#侧码:

void ReceiveData()
{
    client = new TcpClient("192.168.1.85", 64000);
    NetworkStream stream = client.GetStream();
    Byte[] dataReceive = new Byte[256];
    String responseData = String.Empty;
    Int32 bytes = stream.Read(dataReceive, 0, dataReceive.Length);
    responseData = System.Text.Encoding.ASCII.GetString(dataReceive, 0, bytes);
    txtReceive.Text += responseData;
    stream.Close();
}

输出:

data1

1 个答案:

答案 0 :(得分:1)

突然间我得到了自己的答案:

client = new TcpClient("192.168.1.85", 64000);
NetworkStream stream = client.GetStream();
Byte[] dataReceive = new Byte[256];
String responseData = String.Empty;
Int32 bytes;
while ((bytes = stream.Read(dataReceive, 0, dataReceive.Length)) != 0)
{
    responseData = System.Text.Encoding.ASCII.GetString(dataReceive, 0, bytes);
    txtReceive.Text += responseData;
}
stream.Close();

TcpListener对我来说没用,因为我将C#作为客户端运行,而不是服务器。但是感谢@ Bearcat9425,他给出的链接是一个很好的帮助。