我正在使用 JSch 0.1.50 为我的 CI Jenkins 插件建立到远程服务器的连接。假设我在这里尝试使用 session.connect(60000);
超时 60 秒:
Session session = null;
try {
JSch jsch = new JSch();
if (rsaIdentity != null && !rsaIdentity.equals("")) {
jsch.addIdentity(rsaIdentity.trim());
}
session = jsch.getSession(serverLogin, serverHost, Integer.parseInt(serverPort));
session.setPassword(getDescriptor().getOpenPassword(encryptedPasswordString));
session.setConfig("StrictHostKeyChecking", "no"); // not use RSA key
int timeOut = Integer.parseInt(getDescriptor().getConnectionTimeOut());
session.connect(60000);
} catch (SocketTimeoutException e) {
logger.error(e.getMessage());
return false;
} catch (JSchException e) {
logger.error(e.getMessage());
return false;
}
但事实上,在连接到非常慢的服务器期间执行此代码期间,我每次都在大约 20 秒内面临超时 Exception
:
2016-01-25 13:15:55.982 [INFO] Connecting to server: devsrv26:22 as [user] ...
2016-01-25 13:16:16.991 [ERROR] java.net.ConnectException: Connection timed out: connect
2016-01-25 13:16:16.992 com.jcraft.jsch.JSchException: java.net.ConnectException: Connection timed out: connect
2016-01-25 13:16:16.992 at com.jcraft.jsch.Util.createSocket(Util.java:389)
2016-01-25 13:16:16.993 at com.jcraft.jsch.Session.connect(Session.java:215)
2016-01-25 13:16:16.993 at com.mycomp.jenkins.MyPlugin.perform(MyPlugin.java:225)
76991-55982=21008 毫秒
有谁知道这 20 秒超时的原因是什么?
最佳答案
如果您检查 Util.createSocket
是如何实现的,您会看到 timeout
只定义了连接的上限,而不是下限,因为timeout
奇怪地没有传递给底层 Socket
。
这 20 秒可能是操作系统级别的默认限制。
要覆盖它,请尝试实现 SocketFactory
并使用 Session.setSocketFactory
将其附加到 session 中.
在工厂中使用 Socket.connect(SocketAddress endpoint, int timeout)
.
类似于:
public class SocketFactoryWithTimeout implements SocketFactory {
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException
{
socket=new Socket();
int timeout = 60000;
socket.connect(new InetSocketAddress(host, port), timeout);
return socket;
}
public InputStream getInputStream(Socket socket) throws IOException
{
return socket.getInputStream();
}
public OutputStream getOutputStream(Socket socket) throws IOException
{
return socket.getOutputStream();
}
}
关于java - JSch session 超时限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35009009/