1

I want to send/receive strings to/from an ENC28J60 via a C# application. I used my own "protocol" to do this. For example I send "" to Arduino and it replies with a string containing temperature values. This method works fine in Serial communication mode, but freezes in Network mode. What am I missing here? Is there a better method to do this? I'm new to socket programming. I'm using UIPEthernet.h by ntruchsess.

My server-side (Arduino) code:

void checkAndReceiveFromTCPClients(){
  size_t size;
  if (EClient = EServer.available()){
    char* strIn;
    if(size = EClient.available() > 0){
      strIn = (char*)malloc(size + 1);
      memset(strIn, 0, size + 1);
      EClient.read(strIn, size);
    }
    strIn[size] = 0;
    String strInput = String(strIn);
    strInput.trim();
    //This replies to client (sends string) with a string (EClient.write(answer)):
    InterpretInputString(strInput); 
    //EClient.stop();
    EClient.flush();
  }
}

C# code:

string SendAndReceiveOverNet(string Command) {
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(Command);
    NetworkStream stream = TClient.GetStream();
    stream.Write(data, 0, data.Length);
    data = new Byte[256];
    String responseData = String.Empty;
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    return responseData;
}
VE7JRO
  • 2,515
  • 19
  • 27
  • 29
Safa Dana
  • 81
  • 2
  • 9

1 Answers1

1

Something like this is needed here. If you use stream.Read without TClient.Available, the program will freeze or crash.

C# code:

string SendAndReceiveOverNet(string Command) {
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(Command);
    NetworkStream stream = TClient.GetStream();
    stream.Write(data, 0, data.Length);
    String responseData = String.Empty;
    Int32 size = TClient.Available;
    if (size > 0)
    {
        data = new Byte[size];
        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    }
    return responseData;
}