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

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.