WiFi TCP Server receiving and returning String

Hello,

I am trying to create a simple WiFi TCP Server, but I'm stuck. The TCP server will receive a String, should pass the String to another method which will return another String of values. The returned String has to be sent back to the TCP client.

Can you give me a example of such a TCP Server?

Please post your best effort at such a sketch, using code tags when you do, and explain the problems that you are having

My current sketch is this one:

#include <WiFi.h>

const char* ssid = "ssid";
const char* password = "pw";

WiFiServer wifiServer(80);

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");
  Serial.println(WiFi.localIP());
  wifiServer.begin();
}

String executeCommand(String command) {
    if (command == "command") {
    // do stuff
    return "Recv: ok";
  } else {
    //do stuff
    return "Err";
  }
}

void loop() {

  WiFiClient client = wifiServer.available();

  if (client) {

    while (client.connected()) {

      while (client.available() > 0) {
        String received = client.read();
        String returnValue = parseCommand(received);
        client.println(returnValue);
      }

      delay(10);
    }

    client.stop();
    Serial.println("Client disconnected");

  }
}

I'm getting the error "conversion from 'int' to 'String' is ambiguous".

I did also try to receive the String as a 'char' and send the 'char' to the executeCommand method. Did not get any errors, just nothing happened.

        String received = client.read();

client.read() returns a single byte so you cannot compare it with String, hence the error You need to use a function that returns a String, perhaps readStringUntil() as long as the incoming String is terminated in some way

String received = client.readString();

works perfectly fine, thank you very much.

But do you know, why I'm getting two responses from the server?
When I'm sending (for example) "1", and executeCommand returns (for example) "Hello" I'm getting the response
"Hello" from the server and instantly after this response I'm getting a empty response.

Are you by any chance sending a Carriage Return or Linefeed character at the end of your String ?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.