Blocking receive function with TCPClient

Hello.

I am porting a PC application to communicate my Core as TCPServer with one TCPClient. I use on the PC original software a blocking function to receive data -I know the client is sending data constantly- and I have tried to port it to my core using

int receiveData(int len, unsigned char *buffer)
{
int tam = 0;

Serial.println("Waiting to read");
while(!app.available());
Serial.println("Have data");
while(app.available() && (tam < len))
    buffer[tam++] = app.read();
Serial.println("Data read"); 
return tam;

}

where app is the TCPClient that I guarantee to be conected, and the prints are for debugging reasons.

The funcion hangs at random in the while(!app.available()); although I force the client to send data. When testing the same client against my PC server, everything works ok. I know I could implement a non-blocking receive function, and it may solve the problem, but my question is whether is it dangerous -or plainly wrong- to place such a while loop inside the loop() function. That is, if the firmware needs the loop function to end to perform its housekeeping tasks.

Thank you very much for your help.
Regards,
Germán

I have tested the non-blocking version, just protecting each call to receiveData like this:

if (app.avalilable())
receiveData(…);
else return;

to force the loop() function to end, and it works fine. It does not hang at all. Nevertheless I would appreciate any confirmation from the firmware experts.

Regards.

@mermaja, if you want to use the blocking method, just call Spark.process() to allow the firmware to do its thing, like this:

while(!app.available()) Spark.process();

Now, the USER code will “hang” but not the background firmware which does all the wifi/network stuff. You may also want to consider building a timeout in your while() so you don’t wait forever if the network connection is lost. It is always preferred not to block so your second approach is a wiser approach. :smile:

Thank you very much, this Spark.process() call is a neat solution.

As you suggest, I will use the non-blocking approach, but it is good to know about the other possibility. I am beginning with the Core, and many things are left to learn :smile: