我试图在不使用SFTP.disconnect((方法的情况下突然断开Java中的SFTP连接。使用它来构建一个集成测试,检查每次都会进行清理。参见下面的测试:
public void checkDisruptedConnections() throws JSchException, InterruptedException {
ChannelSftp sftp = setupSftp(null);
sftp.connect();
try {
//disrupt connection OVER HERE
} catch (Exception e) {
assertEquals("1", jedis.get(SESSION_KEY));
}
waitForConnectionClose();
assertEquals("0", jedis.get(SESSION_KEY));
}
最终使用了一个单独的线程来连接并中断。
@Test
public void testSftpInterupt() throws InterruptedException, JSchException, SftpException {
Connect thread = new Connect();
thread.start();
while (thread.isAlive()) {
waitForConnectionClose();
}
waitForConnectionClose();
assertEquals("0", jedis.get(SESSION_KEY));
}
Connect如下所示:
private class Connect extends Thread {
@Override
public void run() {
ChannelSftp sftp = null;
Thread thread = this;
SftpProgressMonitor monitor = new SftpProgressMonitor() {
@Override
public void init(int op, String src, String dest, long max) {
}
@Override
public boolean count(long count) {
currentThread().interrupt();
return false;
}
@Override
public void end() {
}
};
try {
sftp.connect();
sftp.put(LOCAL_FILE_LARGE, remoteFile, monitor);
} catch (JSchException | SftpException e) {
assertEquals("java.io.InterruptedIOException", e.getMessage());
}
}
}