在JSch ChannelSftp操作上配置超时

时间:2013-05-14 14:42:26

标签: sftp jsch

我正在使用JSch库从SFTP服务器列出和下载文件。
Channel channel = this.session.openChannel(SFTP_CHANNEL_NAME);
channel.connect();
sftpChannel = (ChannelSftp) channel;
Vector listing = sftpChannel.ls("*");

在调用ls时,应用程序线程有时会卡住。

线程转储 -
Thread 15108: (state = BLOCKED)
java.lang.Object.wait(long) @bci=0 (Compiled frame; information may be imprecise)
java.io.PipedInputStream.read() @bci=142, line=310 (Compiled frame)
java.io.PipedInputStream.read(byte[], int, int) @bci=43, line=361 (Compiled frame)
com.jcraft.jsch.ChannelSftp.fill(byte[], int, int) @bci=17, line=2527 (Compiled frame)
com.jcraft.jsch.ChannelSftp.header(com.jcraft.jsch.Buffer, com.jcraft.jsch.ChannelSftp$Header) @bci=12, line=2553 (Interpreted frame)
com.jcraft.jsch.ChannelSftp.ls(java.lang.String) @bci=298, line=1424 (Interpreted frame)

有没有办法在ls和其他方法上配置超时?我在channel.connect(timeout)看到设置超时,但这只会在连接到远程服务器时设置超时。

3 个答案:

答案 0 :(得分:5)

防止命令粘滞的正确方法是在会话中设置serverAliveInterval。来自源代码:

  /**
   * Sets the interval to send a keep-alive message.  If zero is
   * specified, any keep-alive message must not be sent.  The default interval
   * is zero.
   * @param interval the specified interval, in milliseconds.
   * @see #getServerAliveInterval()
   */
  public void setServerAliveInterval(int interval) throws JSchException {
    setTimeout(interval);
    this.serverAliveInterval=interval;
  }

答案 1 :(得分:1)

检查jsch源代码,看起来不太可能。但它毕竟是开源的,你应该能够实现这一点。看一下ChannelSftp.start中流的初始化。您可以使用可自定义的超时来破解您自己的实现。

答案 2 :(得分:0)

虽然javadoc在millis中说,我认为它实际上在几秒钟内工作。 https://epaul.github.io/jsch-documentation/simple.javadoc/com/jcraft/jsch/Session.html#setServerAliveInterval-int-

            ChannelSftp sftpChannel = (ChannelSftp)session.openChannel("sftp");
            sftpChannel.connect();
            System.out.println("SFTP Channel created.");        
            session.setServerAliveInterval(3);
            filelist = (Vector<ChannelSftp.LsEntry>) sftpChannel.ls("*");

此代码按预期工作,并在3秒内超时

相关问题