Search code examples
javarecursionnetwork-programmingtimeoutjsch

Timeout exceptions ending my code unexpectedly with JSCH


I'm using jsch to send files. I have this piece of code :

public boolean connect()
{ 
    if (_connect()) return true;
    else if (cons_attempts < 3) 
    {
        cons_attempts ++;
        try 
        {
            Thread.sleep(3000);
        } 
        catch (InterruptedException ex){}
        finally
        {
            connect();
        }
    }
    return false;
}

public boolean _connect()
{
    try 
    {
        session = jsch.getSession(user, host, port);
        session.setTimeout(15000);
        session.setConfig("StrictHostKeyChecking","no");
        
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect(15000);
        sftp = (ChannelSftp) channel;
        return true;
    }
    catch (JSchException ex) 
    {
        MyLogger.log(Level.SEVERE, ex.getMessage());
        return false;
    }
}

My code only has problems with timeout exceptions. Before this, I didn't set timeouts to jsch and the log was :

-- java.net.ConnectException: Connexion terminée par expiration du délai d'attente (Connection timed out)

-- bye

With the timeouts it logs :

-- timeout: socket is not established

-- bye

The 1st timeout is not really my problem but the frustrating part is that I don't understant why my program exits after only 1 connection attempt.

With all other exceptions I caught so far, the program did attempt 3 times. What am I missing? What is the cause of my code not trying to connect 2 more times?

Thanks

Edit: -Not sure if it will help but the .jar is executed in a .sh which is executed by a cron job.

-Also the server's OS is Debian.

-According to our network guy, our own firewalls do not seem to be the reason of the timeout.


Solution

  • since you didn't post the full code of the method calling the connect() method, i assumed that you are calling the connect() method which then call the _connect() method. Then if you want the code to try three attempt then the connect() method should be

     public boolean connect(){ 
       int maxAttempt = 3;
       for(int cons_attempts  = 0 ; cons_attempts   < maxAttempt  ; cons_attempts  ++){ 
         if (_connect()) {return true;}
         try 
          {
             Thread.sleep(3000);
          } 
           catch (InterruptedException ex){}
         }
       }
       return false;
     }