0

I want to send some data from Arduino server to C# application and show it in a textbox. But when I try to read the data from C# I only get the first line of sent data.

This is Arduino side code:

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();
 }
}

I think there must be some problem in my C# side code.

C# side code:

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();
}

Output:

data1
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Safa Seed
  • 35
  • 9
  • I have no experience with Arduion but I bet you have to flush() the data on the arduino side. – VVS Jan 09 '18 at 14:37
  • @VVS Already tried, But no answer – Safa Seed Jan 09 '18 at 14:39
  • 2
    I would imagine its cause when you received your first bit of information your receive method is called and then immediately closed I dont see the rest of your code but I would assume it continues on and likely closes the application? Are you listening continuously? Might take a look at this link https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx – Bearcat9425 Jan 09 '18 at 14:47
  • @Bearcat9425 question code updated. just a button calls ReceiveData() in C#. no complicated code. – Safa Seed Jan 09 '18 at 14:51
  • The basic issue is that you didn't bother to read the documentation before you dove in and tried to write network I/O code. See marked duplicates. – Peter Duniho Jan 09 '18 at 22:08

1 Answers1

1

Suddenly I got my own answer:

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 was useless for me, because I'm running my C# as a client, not a server. But thanks to @Bearcat9425, his given link was a good help.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
Safa Seed
  • 35
  • 9