TCPClient.connected returns true until timeout on Photon HTTP request

Hi all,

I’m testing some very basic TCPClient code to do an HTTP request. The server should close the connection but this doesn’t happen and it times out after 2 minutes. Is this a bug with TCPClient?

#include "spark_wiring_tcpclient.h"
#include "application.h"
    
TCPClient client;
    
void setup() {
    while (!Serial.available()) {
        Serial.println("Press any key to start.");
        delay (1000);
    }
    
    if (client.connect("google.com", 80)) {
        Serial.println("connected");
        client.println("GET /search?q=arduino HTTP/1.1");
        client.println("Host: www.google.com");
        client.println("Connection: close");
        client.println();
    }
}
    
void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }
    
      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
    
        // do nothing forevermore:
        while(true);
    }
}

Thanks!
Kev

Is this for a core or photon? You also shouldn’t need the first include

Yes using a Photon. You’re also right that the #include “spark_wiring_tcpclient.h” isn’t required.

@JumpMaster, if you are compiling on the web IDE then I don't believe that client.connected() will correctly return FALSE when the server disconnects. I discussed this issue here:

The fix is available for those who compile locally but not on the web IDE yet. As a temporary fix, you can set a timeout so that when you receive nothing from the server for a set time (5 secs?), you do a client.stop().

That’s good to know. I’m submitting request to emoncms which gives a known reply. So I disconnect after receiving ok which will do for now.

Thanks!

1 Like

For HTTP transactions, you’re also probably better off using HttpClient library instead of TcpClient library.

Provides higher-level functions and seems fairly reliable in my experience so far.

1 Like