[Solved] Problem with TCP Client

I am using TCP Client but is not working all the time. Sometimes it connects and sometimes it just passes a lot of time until it connects again. I am trying to connect to an IP address (Apache Server) over port 80 and if i try to connect from an Java program it works always.

Hey @christian_arias, I know it’s possible that you are simply using the TCPClient example but as always, it’s usually helpful if you could post the code you are working on.

Also, where is the apache server and where is the java server (relative network-wise to the core)?

Hello @harrisonhjones thanks for your answer.

I am trying to connect to my PC that has Apache Server running, and the Java application is just a simple program that uses Socket Connection, I wrote it just to test if the connection works from another device in this case my laptop.

I have 200 lines of code, so better I put just the important part here:

#include "MFRC522.h"
#define SS_PIN SS
#define RST_PIN D2

TCPClient cliente;
byte server[] = { 192, 168, 1, 103 };
int8_t port = 80;
boolean estado;

MFRC522 mfrc522(SS_PIN, RST_PIN);        // Crear instancia del MFRC522

//This function tries to connect

void conectarSTCP(){
    Serial.println("Conectando al Servidor"); //Connecting to the server
    cliente.connect(server, port);
    String m= "Conexión Exitosa a Servidor "; //Success
    String oct1 = String(server[0]);
    String oct2 = String(server[1]);
    String oct3 = String(server[2]);
    String oct4 = String(server[3]);
    String servidor = String(oct1 + "." + oct2 + "." + oct3 + "." + oct4);

     if (cliente.connected()){
        Serial.println(m + servidor);
     } else {
        Serial.println("Falló conexión!"); //No connection

//Just SPI and Serial initialization

void setup() {
     Spark.function("ledws", ledControl);

   // Configure the pins to be outputs
   pinMode(led1, OUTPUT);

   // Initialize both the LEDs to be OFF
   digitalWrite(led1, LOW);
    Serial.begin(9600);        // Inicializar comunicacion Serial
    while(!Serial.available()) SPARK_WLAN_Loop();
    SPI.begin();               // Inicializar comunicacion SPI
    mfrc522.PCD_Init();        // Inicializar el modulo MFRC522111
    pinMode(buzzer, OUTPUT);    //Pin para un buzzer
    digitalWrite(buzzer, LOW);

//This function just test if there is connection

boolean verificarConexion(){
    if (cliente.connected()){
        estado = true;
    } else {
        estado = false;
    return estado;

//This function just send a code to the web service in this case it sends a character just for testing

void sendToWebService(){
    String prueba = "h";
    cliente.println("GET /wishlist/spark.php?code=" + prueba + " HTTP/1.0");
    cliente.println("Host:"); //PC with Apache Server

//Here I use the RFID library to read the UID of a MIFARE tag, after it reads it tries to connect to the server and send the code (in this case a character) to the webService.
Sometimes the connection works all the time but sometimes it just can't connect even if I reset the Core or update my code.

void loop() {
        MFRC522::MIFARE_Key key;
        for (byte i = 0; i < 6; i++) {
                key.keyByte[i] = 0xFF;
        // Buscar tarjetas
        if ( ! mfrc522.PICC_IsNewCardPresent()) {
   // Seleccionar la tarjeta
        if ( ! mfrc522.PICC_ReadCardSerial()) {
        // Ahora que la tarjeta esta seleccionada. El UID (codigo) y el SAK esta en mfrc522.uid.
        // Dump UID
        //Mensaje enviados de forma Serial al PC
        Serial.print("Numero de Bytes: ");
        tipoPICC();         //Inicia la transmision del UID a la PC
        //Call connection function

        if (verificarConexion()){

Hi @christian_arias

There a couple of things I would change in your code. First I would switch server to an IPAddress and port should be a uint16_t but these are not big issues, just clean up.

Here is some code I have used that waits for the return data from the server with a timeout, reads any available data, and then finally flushes and stops the client.

client.connect(server, 80);

if (client.connected()) {
        Serial.println("Connected to server.");
        client.print("GET ");
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println("Connection: close");  //should make the server close after one connection

        unsigned int count = 0;
        unsigned long lastTime = millis();
        while( client.available()==0 && millis()-lastTime<10000) { //ten second timeout
          SPARK_WLAN_Loop()  }  // or do nothing if you don't need the cloud
        lastTime = millis();
        while( client.available() && millis()-lastTime<10000 ) {  //ten seconds
          client.read();  //flush data
        client.flush();  //for safety
        Serial.print("sent and closed-bytes: ");

Thanks for your help @bko I really appreciate it, I will try it and let you know the results

I think this line is important becuase everything is working fine now, thanks

client.println(“Connection: close”);

1 Like

Hi @christian_arias

The two while() loops are also important since just calling flush() does not get the data out of the TI CC3000.

Glad it is working for you!