How to get the client(s)of an Arduino ethernet server?

I would like to implement an inactivity timeout for my clients.
(It seems I cannot connect to my Arduino via ethernet because some connection are not properly closed)

How can I do that?

I have something like:

loop() {

Client incomingClient = server.available();
if (incomingClient) {
[read received command and process it]
} else {
// I enter here if
// no telnet connection
// or no activity on telnet link
incomingClient.println(“disconnecting”); // ← doesn’t work obvisouly due to if condition
incomingClient.stop(); // ← doesn’t work for same reason
}
}

So the question is how can I timeout my ethernet connection?

Thanks,

Emmanuel

I used PuTTY to test this with a very simple “telnet”. It echos your input to the serial monitor until you enter an ‘x’, or don’t do anything for 10 seconds.

Change the network settings to your system.

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip( 192,168,2,2 );
IPAddress gateway( 192,168,2,1 );
IPAddress subnet( 255,255,255,0 );

EthernetServer server(23);

int loopCount = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(4,OUTPUT);
  digitalWrite(4,HIGH);
  Ethernet.begin(mac, ip, gateway, gateway, subnet);
  delay(2000);
  server.begin();
  Serial.println("Ready");
}

void loop()
{
  EthernetClient client = server.available();

  if(client)
  {
    Serial.println("Client connected");
    client.flush();
    Serial.flush();
    loopCount = 0;
    
    while (client.connected()) 
    {
      while(client.available()) 
      {
        char c = client.read();

        if(c == 'x') client.stop();
        else Serial.write(c);

        loopCount = 0;
      }

      while(Serial.available()) client.write(Serial.read());

      delay(1);
      
      loopCount++;

      if(loopCount > 10000) client.stop();      
    }

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

edit: My bad. I forgot one client.stop(). Fixed.
This is a persistent connection. It does not close until you tell it to.

I also added a serial response. While the client is connected, you can send messages to the connected client with the serial monitor input.