TCPClient to connect to webserver

try this code instead, add these 2 functions after the main loop() function. To make sure we are going super fast in the out() function we are using client.write instead of client.print and the in() function makes sure everything gets flushed nicely and has some timeouts so we dont hang the core if the server doesn’t reply.

/*----------------------------------------------------------------------*/
/* out - outputs supplied string to TCPclient */
void out(const char *s) {

client.write( (const uint8_t*)s, strlen(s) );

if (DEBUG)Serial.write( (const uint8_t*)s, strlen(s) );

}
/*----------------------------------------------------------------------*/

/*----------------------------------------------------------------------*/
/* in - reads from TCPclient, with timeout */
void in(char *ptr, uint8_t timeout) {
        int pos = 0;
        unsigned long lastTime = millis();
        
        while( client.available()==0 && millis()-lastTime<timeout) { //timeout
        }  //do nothing
        lastTime = millis();
        unsigned long lastdata = millis();
        
        while ( client.available() || (millis()-lastdata < 500)) {  //500 millisecond timeout
            if (client.available()) {
                char c = client.read();
                if(DEBUG)Serial.print(c);
                lastdata = millis();
                ptr[pos] = c;
                pos++;
            }
            if (pos >= 512 - 1)
            break;
        }
        ptr[pos] = '\0'; //end the char array
        while (client.available()) client.read(); // makeshift client.flush()
        client.flush();  //for safety
        delay(400);
        client.stop();
        if(DEBUG){
            Serial.println();
            Serial.print("Done, Total bytes: ");
            Serial.println(pos);
        }
        
}
/*-----------------------------------------------------------------------*/

and here is your code from above modified to use the 2 new functions

Serial.println("Connecting to web server: ");
if (client.connect(server, port)) {
    Serial.println("Connected...");
    out("GET /spark/add_data.php?dt=1421688456&id_spark=1234568ff&id_user=788 HTTP/1.1\r\n");
    out("Host: ubuntu.ashnet\r\n");
    out("User-Agent: Spark/1.0\r\n");
    out("Content-Type: text/html\r\n");
    out("Connection: close\r\n\r\n");
    Serial.println("Send data to server - valore: " + io );        
Serial.println("Closing Connection...");
in(reply, 3000);
} 
else {
Serial.println("Connection failed");
Serial.println("Disconnecting.");
client.stop();
}

and add this before setup()

boolean DEBUG = false; // enable or disable Debug output
char reply[512]; // the server reply is saved in this.. you could parse it for data if needed.
1 Like