How to make robust client-server connection?

Like the title says I’m trying to figure out how make client-server connection which recovers from all sorts of hang-on situations etc.

In my project I use <MKRNB.h> library and below is basic working code for sending some data to server. For how long library tries to open connection to server? How does it decide to stop creating the connection? How to make sure it doesn’t hang? Does it make sense to keep retrying?

  if (client.connect(server, port)) {                     
    client.print("POST ");
    client.print(dataPath);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded"); 
    client.print("Content-Length: "); 
    client.println(strlen(dataInJSON)); 
    client.println(); 
    client.print(dataInJSON); 
  }

Thanks,

tipo

Last I checked, this worked okay. Change the IP settings to match your localnet.
[code]
#include <SPI.h>
#include <Ethernet.h>
#include <SdFat.h>

SdFat sd;

byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,2);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

// IPAddress server(192,168,1,29); // Local
// IPAddress server(206,188,192,135);
char server[] = "www.prolectron.com";

EthernetClient client;
File fh;
char host[] = "prolectron.com";
char file_path[] = "";
char fileName[] = "default.html";

int totalCount = 0;
int loopCount = 0;
char pageAdd[48];

void setup() {
  Serial.begin(115200);

  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);

  pinMode(10,OUTPUT);
  digitalWrite(10,HIGH);

  if(!sd.begin(4)) {
    Serial.println("SD fail");
    while(true);
  }

//  Ethernet.begin(mac, ip, gateway, gateway, subnet);

  if(!Ethernet.begin(mac)) {
    Serial.println("dhcp fail");
    while(true);
  } else Serial.println(Ethernet.localIP());

  Serial.println("Ready. Press 'f' or 'r'");
}

void loop()
{
  byte inChar;

  inChar = Serial.read();

  if(inChar == 'f')
  {
    if(doHTTP()) Serial.println("HTTP OK");
    else Serial.println("HTTP FAIL");
  }

  if(inChar == 'r')
  {
    readSD();    
  }

}


byte doHTTP()
{
  int lncount = 0;
  char outBuf[65];
  bool hdr_done = false;
  bool failed = false;
  
  Serial.println("Starting request");
  sprintf(pageAdd,"%s/%s",file_path,fileName);

  Serial.print("connecting...");

  if(client.connect(server,80))
  {
    Serial.println("connected");

    sprintf(outBuf,"GET %s HTTP/1.1\r\nHost: %s\r\n",pageAdd,host);
    client.write(outBuf);
    Serial.print(outBuf);
    sprintf(outBuf,"User-Agent: Mozilla/5.0\r\nAccept: */*\r\n");
    client.write(outBuf);
    Serial.print(outBuf);
    sprintf(outBuf,"Connection: close\r\n\r\n");
    client.write(outBuf);
    Serial.print(outBuf);

  } 
  else
  {
    Serial.println("Connect failed");
    return 0;
  }

  lncount = client.readBytesUntil('\n',outBuf,64);
  outBuf[lncount] = 0;

  if(strncmp("HTTP/1.1 200",outBuf,12) != 0) {
    Serial.println("Request failed");
    failed = true;  
  }

  Serial.println(outBuf);

  while(client.connected())
  {
    lncount = client.readBytesUntil('\n',outBuf,64);
    outBuf[lncount] = 0;
    
    if(lncount < 2 && hdr_done == false) {
      Serial.println("Header done");
      hdr_done = true;
    }

    if(hdr_done == false) Serial.println(outBuf);
    else if(!failed) {

      if(!sd.exists(file_path)) {
        if(!sd.mkdir(file_path)) {
          Serial.println("mkdir failed");
        }
      } else {
        Serial.println("directory exists");
      }

      if(!sd.chdir(file_path)) {
        Serial.println("chdir failed");    
      }
      
      sd.remove(fileName);
      fh = sd.open(fileName,FILE_WRITE);
      if(!fh)
      {
        Serial.println("SD open fail");
        client.stop();
        return 0;    
      }
      

      while(client.connected())
      {
        while(client.available())
        {
          byte c = client.read();
          fh.write(c);      
        }
      }

      fh.close();
      Serial.println("SD closed");
    }
  }

  Serial.println("disconnecting.");
  client.stop();

  if(failed) return 0;
  else return 1;
}

void readSD()
{
  Serial.println("SD read");

  if(!sd.chdir(file_path)) {
    Serial.println("chdir failed");    
  }

  fh = sd.open(fileName,FILE_READ);

  if(!fh)
  {
    Serial.println("SD open fail");
    return;    
  }

  while(fh.available())
  {
    Serial.write(fh.read());
  }
  
  fh.close();
  Serial.println("Done");
}
[/code]

Hi, I guess the only way to detect all kinds of possible errors is through time-outs. For example client.readBytesUntil('\n' may be waiting a long time if the client doesn't send \n at all.

This is the reason I prefer using sockets (you can set time-out on the socket which doesn't have to be very long for HTTP, a few seconds would do just fine).

Another problem that occurs every now and then is also losing WiFi connection. HTTP server should be able to detect this and reconnect when possible.

An example of socket HTTP server can be found here: GitHub - BojanJurca/Multitasking-Esp32-HTTP-FTP-Telnet-servers-for-Arduino: ESP32 with HTTP server, Telnet server, file system, FTP server FTP client, SMTP client, cron daemon and user management