8

I am using JSch library to list and download files from a SFTP server.

Channel channel = this.session.openChannel(SFTP_CHANNEL_NAME);
channel.connect();
sftpChannel = (ChannelSftp) channel;
Vector<LsEntry> listing = sftpChannel.ls("*");

While calling ls, application thread is getting stuck sometimes.

Thread dump -

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)

Is there a way to configure timeout on ls and other methods? I saw setting timeout on channel.connect(timeout) but this only sets the timeout while connecting to remote server.

4

3 回答 3

9

防止命令粘连的正确方法是在会话上设置 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;
  }
于 2013-11-06T12:21:02.013 回答
2

检查jsch源代码,它看起来不像是可能的。但它毕竟是开源的,你应该能够实现它。看看ChannelSftp.start. 您可以使用可自定义的超时来破解您自己的实现。

于 2013-05-15T08:00:51.540 回答
0

尽管 javadoc 以毫秒为单位,但我认为它实际上可以在几秒钟内工作。 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 秒内超时

于 2017-01-24T00:04:10.053 回答