0

Look at the trick in the last few lines of this code:

#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "yyyyyyy";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

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

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
     delay(500);
     Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

 int delays = 0;

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
    delay(1);
    delays++;  // First line of trick.
    if (delays > 10) {
       return;
    } // Trick ends.
  }
  ...// Handle some events.
}

Code works ok without the trick (only delay(1); inside the loop), but the problem is it gets stucked there, if some responses are asked from browser so that tab is closed in between the requests.

One response is for favicon:

 if (req.indexOf("favicon.ico") != -1) {
    String s = "HTTP/1.1 404 WTF Favicon !!\r\n";
    client.print(s);
    client.flush();
    return;
 }

I had also one similar response starting with 200 OK for certain URLs and then a response of plain json text.

I would like to know why my server gets stucked on this delay(1);? Also, when the trick is needed, what is correct delays value?

Also I did add a client.flush(); after every client.print();. May that affect anything?

1

WifiServer class has a bug that is now resolved. It causes a phenomenom described like follows:

When I send message to client via WifiServer.avalible, the user is disconnected from server - I can connect to it again, so server is not stopping.

And latest comment on topic is that it is corrected in latest commits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.