0

我试图在不使用 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));
}
4

1 回答 1

0

最终使用了一个单独的线程来连接并被中断。

@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));
}

连接如下所示:

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());
        }
    }
}
于 2022-02-28T22:13:21.420 回答