Arduino stuck on lost Ethernet connection. How to prevent it.

Hello, I have Controllino Mega with W5100. Everything is basically Arduino mega.

I use direct Ethernet cable to PC to send and recieve data. Controller acts like a server. I use KiTTy to connect. Everything works fine.

However in the even of disconnecting Ethernet cable it hangs and doesn't perform any other actions. (but still counts encoder perfectly). It comes back when I connect the cable.

is there a way to prevent this?

I tried set retransmission timeout but it dosen't seem to have any effect.

I didin't post full code as its over 1000 lines....

//-----setup---//
  Ethernet.setRetransmissionTimeout(50);
} // --- end of setup

void loop() {
  EthernetClient newClient = server.accept();
  if (newClient) {
    client = newClient;
    client.println("Connected");
    client.println("Current = ");
    client.println(actualPos);
  }
  actualPos = myEnc.read() / (encoderConst / 1000); // convert siganls to mm.
  if (abs(actualPos - oldPosition) > 0.2) {
    oldPosition = actualPos;

    if (client.connected()) {
      client.print("Current = ");
      client.print(actualPos);
      client.print("    Target= ");
      client.println(position2reach);
    }
  }

  if (client.available() > 0) {
    byte thisByte = client.read();


//--- other stuff---

don't call accept in very loop()
or use
EthernetClient newClient = server.available();

accept() will return the client only once

I am not sure how does available help or how exactly to use it(sorry I am new to Ethernet).

I modified my code so it doesn't .accept when its doing something important however it seems it hangs on client.print.

maybe there is a way to do a time out on client.print?

void loop() {

  
  if (!client.connected() && motorStopped == 1){
  EthernetClient newClient = server.accept(); 
  if (newClient) {
    client = newClient;
    client.println("Connected");
    client.println("Current = ");
    client.println(actualPos);
  }}

  actualPos = myEnc.read() / (encoderConst / 1000); // convert siganls to mm.
  if (abs(actualPos - oldPosition) > 0.2) {
    oldPosition = actualPos;
      if (client.connected()){
      client.print("Current = ");
      client.print(actualPos);                  // hangs somewhere here i think
      client.print("    Target= ");
      client.println(position2reach);
    }}

Solved finally,

I used

Ethernet.setRetransmissionTimeout(10)

Ethernet.setRetransmissionCount(2)

client.setConnectionTimeout(10)

Seems to be working fine so far.