Arduino icon indicating copy to clipboard operation
Arduino copied to clipboard

WiFi shield client does not release socket on connect fail (with fix)

Open SurferTim opened this issue 13 years ago • 5 comments

The wifi shield client code is not releasing the socket when the connection fails. This results in the client using all the sockets in 4 failed attempts, and the connection will fail until the Arduino is reset/rebooted. IDE v1.0.5 and v1.5.5. Here is the fix. This is in WiFiClient.cpp

int WiFiClient::connect(IPAddress ip, uint16_t port) {
    _sock = getFirstSocket();
    if (_sock != NO_SOCKET_AVAIL)
    {
        ServerDrv::startClient(uint32_t(ip), port, _sock);
        WiFiClass::_state[_sock] = _sock;

        unsigned long start = millis();

        // wait 4 second for the connection to close
        while (!connected() && millis() - start < 10000)
            delay(1);

        if (!connected())
    {

// Add this
            WiFiClass::_state[_sock] = -1;
// end of add

            return 0;
        }
    }else{
        Serial.println("No Socket available");
        return 0;
    }
    return 1;
}

SurferTim avatar Dec 05 '13 10:12 SurferTim

If I am not wrong, this should be merged with https://github.com/arduino/Arduino/issues/1637.

fpoto avatar Dec 07 '13 09:12 fpoto

No. This is a separate issue. UDP does not establish a connection like TCP. The section of code this bug is in has nothing to do with UDP. I provided a fix above that has been tested. It was simply a single line omission in the code.

If you think it is the same, install the fix above and try UDP. It won't fix the UDP problem.

This is tested on IDE v1.0.5 with the v1.1.0 firmware upgrade.

I tested UDP and did not find the socket release problem discussed in the other issue.

Here is my socket test. Install it and call it between UDP transactions. It was instrumental in troubleshooting the client socket fail.

void ShowSockStatus() {
  for(int x = 0; x < MAX_SOCK_NUM; x++) {
    Serial.print(WiFi._state[x]);    
    Serial.print("  ");
    Serial.println(WiFi._server_port[x]);    
  }
}

SurferTim avatar Dec 07 '13 10:12 SurferTim

... // wait 4 second for the connection to close while (!connected() && millis() - start < 10000) ...

I believe that is 10 seconds, not 1 second. I.e. 1000 ms = 1 second. 10000 ms = 10 seconds.

ilovetogetspamed avatar Jun 20 '14 16:06 ilovetogetspamed

I tried the fix you suggested, but even after calling client.close(), I still have some ports in use. I'm using IDE 1.0.5-r2 and WiFi shield firmware 1.1.0

danolson1 avatar Sep 10 '14 19:09 danolson1

This issue was moved to arduino-libraries/WiFi#5

agdl avatar Jul 12 '16 13:07 agdl