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,51519 gold badges27 silver badges29 bronze badges
asked Dec 31, 2017 at 16:55

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;
}
answered Sep 17, 2023 at 18:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.