正确检查FTP服务器连接

Mic*_*l A 7 java ftp ftp-client

我在程序开始时打开了与FTP服务器的连接.

在我在服务器上执行操作之前,我想检查连接是否已成功建立.最简单的快速方式,如果连接消失,我会尝试再次连接.

我使用此代码执行此操作:

private boolean checkConnection()
{
    try 
    {
        boolean success = ftpClient.login(user_name, password);
        if(success)
            return true;
        else 
            return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这个方法在连接关闭时抛出NullPointer异常.

我可以检查与之的连接,ftpClient.connect(server, port);但这就像是要重新连接.

有什么方法可以检查连接?

Mic*_*l A 13

尝试发送简单sendNoOp()并检查回复可能是轻松检查连接的好方法:

private boolean checkConnectionWithOneRetry()
{
    try 
    {
        // Sends a NOOP command to the FTP server. 
        boolean answer = ftpClient.sendNoOp();
        if(answer)
            return true;
        else
        {
            System.out.println("Server connection failed!");
            boolean success = reconnect();
            if(success)
            {
                System.out.println("Reconnect attampt have succeeded!");
                return true;
            }
            else
            {
                System.out.println("Reconnect attampt failed!");
                return false;
            }
        }
    }
    catch (FTPConnectionClosedException e) 
    {
        System.out.println("Server connection is closed!");
        boolean recon = reconnect();
        if(recon)
        {
            System.out.println("Reconnect attampt have succeeded!");
            return true;
        }
        else
        {
            System.out.println("Reconnect attampt have failed!");
            return false;
        }

    }
    catch (IOException e) 
    {
        System.out.println("Server connection failed!");
        boolean recon = reconnect();
        if(recon)
        {
            System.out.println("Reconnect attampt have succeeded!");
            return true;
        }
        else
        {
            System.out.println("Reconnect attampt have failed!");
            return false;
        }   
    }
    catch (NullPointerException e) 
    {
        System.out.println("Server connection is closed!");
        boolean recon = reconnect();
        if(recon)
        {
            System.out.println("Reconnect attampt have succeeded!");
            return true;
        }
        else
        {
            System.out.println("Reconnect attampt have failed!");
            return false;
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)