超时异常以 JSCH 意外结束我的代码

Timeout exceptions ending my code unexpectedly with JSCH

我正在使用 jsch 发送文件。我有这段代码:

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;
    }
}

我的代码只有超时异常有问题。在此之前,我没有为 jsch 设置超时,日志是:

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

-- bye

超时记录:

-- timeout: socket is not established

-- bye

第一次超时并不是我的问题,但令人沮丧的是我不明白为什么我的程序仅在尝试 1 次连接后就退出了。

除了我目前捕获的所有其他异常,该程序确实尝试了 3 次。我错过了什么?我的代码没有尝试再连接 2 次的原因是什么?

谢谢

编辑: -不确定它是否有帮助,但 .jar 是在由 cron 作业执行的 .sh 中执行的。

-服务器的OS也是Debian。

-根据我们网管的说法,我们自己的防火墙好像不是超时的原因。

因为您没有 post 调用 connect() 方法的方法的完整代码,我假设您正在调用 connect() 方法,然后调用 _connect() 方法。然后,如果您希望代码尝试三次,则 connect() 方法应为

 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;
 }