WiFiServer: How to get string on server? (SOLVED)

Hi everyone,

Server (ESP32):

void loop() { 

  WiFiClient webclient = server.available();   // Listen for incoming clients

  if (webclient) {                             // If a new client connects,
    Serial.println("New Webclient.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (webclient.connected()) {            // loop while the client's connected
      if (webclient.available()) {             // if there's bytes to read from the client,
        char c = webclient.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            webclient.println("HTTP/1.1 200 OK");
            webclient.println("Content-type:text/html");
            webclient.println("Connection: close");
            webclient.println();
            break;

          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }

        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }

}

Client (ESP8266):

  HTTPClient http;
  String url = "http://192.168.0.240";
  http.begin(url); 
  int httpCode = http.POST("Message from ESP8266");  
  if (httpCode > 0) { 
      String payload = http.getString();   
      Serial.println(payload);                     
   }

Server serial monitor output:

New Webclient.
POST / HTTP/1.1
Host: 192.168.0.240
User-Agent: ESP8266HTTPClient
Connection: close
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0
Content-Type: text/plain
Content-Length: 20

Content-Length: 20 = server successfully received message from client http.POST("Message from ESP8266")

But... how to displaying the message content and send it to serial monitor on server?

Please help...

Thanks.

But… how to displaying the message content and send it to serial monitor on server?

Without seeing ALL of your code, all I can suggest is “with the proper code”.

now you stop reading the client after headers (empty line). continue to read the data from client

PaulS:
Without seeing ALL of your code, all I can suggest is “with the proper code”.

Here is the COMPLETE code.

Server (ESP32):

#include <WiFi.h>

// Set web server port number to 80
WiFiServer server(80);
String header;


const char* ssid     = "SSID";
const char* password = "PASSWORD";

IPAddress local_IP(192, 168, 0, 240);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);   
IPAddress secondaryDNS(8, 8, 4, 4); 

void setup () {
 
   Serial.begin(115200);
   Serial.println(""); 
   
  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }
  delay(5000);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }
  Serial.printf("BSSID: %s\n", WiFi.BSSIDstr().c_str());
  Serial.println("Connected to wifi");
  printWifiStatus();

  
  server.begin();
  
}


void loop() { 

  WiFiClient webclient = server.available();   // Listen for incoming clients

  if (webclient) {                             // If a new client connects,
    Serial.println("New Webclient.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (webclient.connected()) {            // loop while the client's connected
      if (webclient.available()) {             // if there's bytes to read from the client,
        char c = webclient.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            webclient.println("HTTP/1.1 200 OK");
            webclient.println("Content-type:text/html");
            webclient.println("Connection: close");
            webclient.println();
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    webclient.stop();
    Serial.println("Webclient disconnected.");
    Serial.println("");
  }

  
}


void printWifiStatus() {
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Primary DNS: ");
  Serial.println(primaryDNS);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

Client (ESP8266)::

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

//Static IP address configuration
IPAddress staticIP(192, 168, 0, 241); 
IPAddress gateway(192, 168, 0, 230);   
IPAddress subnet(255, 255, 255, 0);  
IPAddress primaryDNS(8, 8, 8, 8);  
 
//SSID and Password of your WiFi router
const char* ssid = "SSID";
const char* password = "PASSWORD";



void setup(void){ 

  Serial.begin(115200);
  Serial.print("MAC: ");
  Serial.println(WiFi.macAddress());
  
  WiFi.begin(ssid, password);
  WiFi.config(staticIP, primaryDNS, gateway, subnet);
  WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only
  Serial.println("Connecting Wifi...");
  delay(5000);
  
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("NOT Connected to wifi");
    WiFi.begin(ssid, password);     //Connect to your WiFi router
    WiFi.config(staticIP, primaryDNS, gateway, subnet);
    WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only
    delay(5000);
  }
 
  //If connection successful show IP address in serial monitor
  Serial.println("Connected to wifi");
  Serial.printf("BSSID: %s\n", WiFi.BSSIDstr().c_str());
  printWifiStatus();

}


void loop(void){
     
  Serial.println("Message from ESP8266-2");
  HTTPClient http;     
  String url = "http://192.168.0.240";
  http.begin(url); 
  http.addHeader("Content-Type", "text/plain");  //Specify content-type header
  int httpCode = http.POST("Message from ESP8266");   //Send the request
  if (httpCode > 0) { 
      String payload = http.getString();   
      Serial.println(payload);                     
   }       
   
  http.end();   //Close connection

}




void printWifiStatus() {
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Primary DNS: ");
  Serial.println(primaryDNS);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

Hope it clear enough for you to be able to help me

Juraj:
now you stop reading the client after headers (empty line). continue to read the data from client

How to continue reading client data?

Please show me...

Sorry, I am just a beginner

Why do you want to use POST, instead of GET? POST is usually used when there is a need to hide the data being sent to the server. I can't see any reason to do that in your case.

How to continue reading client data?

Check client.available(). If the value is non-zero, there is still data to read.

while(client.connected())
{
   while(client.available() > 0)
   {
      // read the data
   }
}

PaulS:
Why do you want to use POST, instead of GET? POST is usually used when there is a need to hide the data being sent to the server. I can't see any reason to do that in your case.

Sorry for that, as I said before I am just a beginner, trying to learn the proper way to do it. I will change to GET

PaulS:
Check client.available(). If the value is non-zero, there is still data to read.

while(client.connected())

{
  while(client.available() > 0)
  {
      // read the data
  }
}

I know while client still connected then there is some data to read. But how to do the reading? That is my problem since beginning and that is why I am asking help in this forum, I don't know how to read client data.

Please just show me. sorry if I am so dumb and annoying.

But how to do the reading?

What would you guess that client.read() does? It's the same function that you use to read the data up to the empty line. Keep using it to read the data after the blank line.

PaulS:
What would you guess that client.read() does? It's the same function that you use to read the data up to the empty line. Keep using it to read the data after the blank line.

Try simplified the server code.

Read all data while client available and remove blank line filter as Paul suggested.

void loop() { 

  WiFiClient webclient = server.available();   // Listen for incoming clients

  if (webclient) {                             // If a new client connects,
    Serial.println("New Webclient.");          // print a message out in the serial port
    while (webclient.connected()) {            // loop while the client's connected
      if (webclient.available()) {             // if there's bytes to read from the client,
        
        Serial.println("Read client data : ");
        Serial.println(webclient.readString());
      
    }
    // Close the connection
    webclient.stop();
    Serial.println("Webclient disconnected.");
    Serial.println("");
  }

Server serial monitor output:

New Webclient.
Read client data : 
POST / HTTP/1.1
Host: 192.168.0.240
User-Agent: ESP8266HTTPClient
Connection: close
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0
Content-Type: text/plain
Content-Length: 20

Message from ESP8266
Webclient disconnected.

The client message string "Message from ESP8266" shows after blank line Content-Length: 20 and before Webclient disconnected.

Thanks a lot Paul for kindly guiding me.... :slight_smile: :slight_smile: :slight_smile: