I'm trying to get two ESPs to communicate with each other using the below code in a client / server format using the Arduino WIFI library. Essentially, what I want is something like the below conversation:
client: Server are you there?
server: I'm here
server: Send me Temp Reading
client: Temp reading - 72 degree F
server: do something
client: done
I've been able to read the first line printed to the server from the client, but the second line doesn't come through. The line printed or written by the server to the client doesn't seem to work either. I'm certain it is either something I don't understand about how wifi comm works or something about the syntax that I'm not grasping.
I'm only posting the void loop code, as the remainder of the code works just fine from what I can tell. I've tried modifying the code in dozens of different setups (adding delays in different locations, flushing, stopping and reconnecting, etc.) based on research on the topic, but I'm missing something.
CLIENT SIDE
void loop () {
digitalWrite(ledPin,LOW);
client.connect(server, 80); // Connection to the server
Serial.println(".");
//to server
client.println("1\r"); // sends the message to the server
//from server
String answer = client.readStringUntil('\r');
//to server
client.flush();
delay(5000);
client.println("2\r");
digitalWrite(ledPin, HIGH);
delay(2000); // client will trigger the communication after two seconds
}
SERVER SIDE
void loop () {
WiFiClient client = server.available();
if (client){
while (client.connected()) {
if (client.available()>0){
digitalWrite(ledPin, HIGH); // to show the communication only (inverted logic)
Serial.println(".");
//to server
String request = client.readStringUntil('\r'); // receives the message from the client
Serial.println(request);
//................................................
if (request == "1") {
Serial.print("Client Sending Temp: Acknowledged"); Serial.println(request);
} else {
Serial.print("Client Sending Temp: Failed"); Serial.println(request);
}
server.write("Send Temp Reading");
//................................................
if (request == "2") {
Serial.print("From client 2.2: "); Serial.println(request);
digitalWrite(ledPin, HIGH);
} else {
Serial.print("From client 2.1: "); Serial.println(request);
}
//................................................
client.flush();
client.stop(); // terminates the connection with the client
}
}
}
}
In the serial monitor all I get back is:
.
1
Client Sending Temp: Acknowledged1 (this is reading the first line from the client)
From client 2.1: 1 (this is acknowledging that the second line isn't reading).
This just repeats over and over again.