I'm using WeMos D1 R2. I'm trying to listen to both ports 1992 and 1993. This is my current code: #include

WiFiServer server_1992(1992);
WiFiServer server_1993(1993);

void setup() {
    WiFi.begin("MySSID", "MyPassword");
    while (WiFi.status() != WL_CONNECTED){
    Serial.println(" connected");


void check_server(WiFiClient* client, WiFiServer* server, const char* text){
    if (client->connected()) { 
        if (client->available()){
            unsigned char c[250];
            client->readBytes(c, 1);
            Serial.print(" ");
    } else {
        client->stop(); //Adding it here like Juraj said. Not tested.
        *client = server->available();     
        if (*client) Serial.print(text);        

void loop() {
    WiFiClient client_1992, client_1993; 
    while (1){
        check_server(&client_1992, &server_1992, "1992 connected \n");
        check_server(&client_1993, &server_1993, "1993 connected \n");       

The problem is when the client(s) disconnect from the hotspot, my code keeps waiting for data forever without trying to acquire new client (with client = server->available();).

Solution: for now I ask the client "Hey are we still connected?" every few seconds and manually kick the client out if it doesn't reply. More on this

Sorry if it's wrong to link other question here, I just hope people who have the same problem as mine can find the solution.

  • stop the client if it is not connected – Juraj May 10 '18 at 10:16
  • If i understand it correctly, you mean close the client from the client side right (not the server side)? The disconnection happens when my phone turn off / disconnect from wifi so I don't think I can close the connection properly? – MoonFan May 10 '18 at 11:02
  • no. stop the esp8266 side of the socket when it is not connected, before you ask if new client is available. there are more tcp states of the connection and after the client side disconnects, it is not established (what connected tests), but not closed either – Juraj May 10 '18 at 11:05
  • I will test it when I can get back home, is it like the one I added to the code ?(before the *client = server->available(); ) – MoonFan May 10 '18 at 11:12
  • yes, that is what I meant. I am not sure if it helps, so I do not write it as answer until you test it. I use extensively esp8266 from Atmega over WiFi Link at it has it's own tricks. there the stop() solves this kind of problem – Juraj May 10 '18 at 11:22

Your Answer

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

Browse other questions tagged or ask your own question.