Having troubles syncing when TCP server or client is running?

The reason is because that longer delay of 5 seconds is also secretly processing the background tasks which is looking for the incoming re-flashing command.

Your client code is also blocking the user loop() from ending for a while, and the Spark Core won’t be able to see the reprogramming command until that happens… or if you add some delay()'s like you figured out.

Another way to do this if you don’t want to have that long delay in your application code… just look for an input to be shorted to ground in setup(), and if it is… loop forever processing the background tasks. Then re-flash your part… when you see it flashing magenta, remove the short so that when it resets it will power up and run. If you forget to remove the short, it will run as soon as you do.

void setup()
{
  pinMode(D7, OUTPUT);

  // ==============================================================
  // if D2 input is LOW, loop here forever processing the B/G tasks
  pinMode(D2, INPUT_PULLUP);
  while( !digitalRead(D2) ) SPARK_WLAN_Loop();
  // ==============================================================
}

void loop()
{
  // Blink slow (this is our fake application)
  digitalWrite(D7, HIGH);
  delay(1000);
  digitalWrite(D7, LOW);
  delay(1000);
}

You could also put this in your loop() so that you don’t have to reset you Core. I’ve also made the D7 LED turn on solid to let us know when our loop() hooks into this special reprogramming loop. Don’t add any other code here or that will actually delay your reflashing process. It’s complicated a bit, but because we are forcing the background tasks to run, it can’t lock out the user code from running like it normally does when our code runs to the end of the user loop() and returns control to the spark core’s main() loop. So if we made the led blink fast in our little while() loop, you’d see the magenta flashing rate match the led flashing rate, because it’s allowing one chunk of data to be received each time SPARK_WLAN_Loop() is called. So if we don’t do much, and call it a lot, it will get done much faster.

void setup()
{
  pinMode(D7, OUTPUT);
  pinMode(D2, INPUT_PULLUP);
}

void loop()
{
  // ==============================================================
  // if D2 input is LOW, loop here forever processing the B/G tasks
  while( !digitalRead(D2) ) {
    SPARK_WLAN_Loop();
    // Turn on D7 led solid so we know it's time to re-flash!
    digitalWrite(D7, HIGH);
  }
  // ==============================================================
  
  // Blink slow (this is our fake application)
  digitalWrite(D7, HIGH);
  delay(1000);
  digitalWrite(D7, LOW);
  delay(1000);
}