【问题标题】:TCP Client doesn't receive all of data from Arduino Ethernet Server [duplicate]TCP 客户端未从 Arduino 以太网服务器接收所有数据 [重复]
【发布时间】:2018-06-18 14:48:05
【问题描述】:

我想将一些数据从 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

【问题讨论】:

  • 我没有使用 Arduion 的经验,但我敢打赌你必须在 arduino 端刷新()数据。
  • @VVS 已经试过了,但是没有答案
  • 我会想象它的原因,当您收到您的第一条信息时,您的接收方法被调用然后立即关闭我没有看到您的其余代码,但我认为它会继续并可能关闭应用程序?你在不停地听吗?可以看看这个链接msdn.microsoft.com/en-us/library/…
  • @Bearcat9425 问题代码已更新。只是一个按钮在 C# 中调用 ReceiveData()。没有复杂的代码。
  • 基本问题是您在投入并尝试编写网络 I/O 代码之前没有费心阅读文档。查看标记的重复项。

标签: c# arduino


【解决方案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,他给出的链接是一个很好的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多