2013-05-14 1522 views
5

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

在调用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)上看到了设置超时,但这只会在连接到远程服务器时设置超时。

回答

1

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

4

防止命令粘连的正确方法是在会话上设置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; 
    } 
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秒内

+0

以我的版本,这是0.1.53,参数超时'如在该文档中指定setServerAliveInterval'被解释,在**毫秒**。 – bskp 2017-06-22 06:49:27