简体   繁体   中英

Configuring timeout on JSch ChannelSftp operations

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.

The correct way to do prevent commands from sticking is to set serverAliveInterval on the session. From the sourcecode:

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

Checking the jsch source code, it does not look like it is possible. But it's open source after all, you should be able to implement this. Take a look at initialization of streams in ChannelSftp.start . You can hack-in your own implementation with customizable timeouts.

Though javadoc says in millis, i think its actually working in seconds. 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("*");

This code is working as expected and timing out in 3 seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM