Java 正确检查FTP服务器连接
我在程序开始时打开与FTP服务器的连接 在服务器上执行操作之前,我想检查连接是否已成功建立。最简单快捷的方式,因此如果连接已断开,我将尝试再次连接 我使用此代码执行此操作:Java 正确检查FTP服务器连接,java,ftp,ftp-client,Java,Ftp,Ftp Client,我在程序开始时打开与FTP服务器的连接 在服务器上执行操作之前,我想检查连接是否已成功建立。最简单快捷的方式,因此如果连接已断开,我将尝试再次连接 我使用此代码执行此操作: private boolean checkConnection() { try { boolean success = ftpClient.login(user_name, password); if(success) return true;
private boolean checkConnection()
{
try
{
boolean success = ftpClient.login(user_name, password);
if(success)
return true;
else
return false;
}
}
但此方法在连接关闭时引发NullPointer异常
我可以使用ftpClient.connect(服务器、端口)检查连接代码>但这就像重新连接一样
bes检查连接的方法是什么?尝试发送一个简单的sendNoOp()
并检查回复可能是轻松检查连接的好方法:
private FTPClient ftp = null;
private void connect()
{
ftp = new FTPClient();
try {
ftp.connect("Server",port);
boolean login = ftp.login("username", "password");
System.out.println(" login "+ login );
} catch (FTPConnectionClosedException e) {
System.err.println("ERROR :: FTP Server Unreachable");
sleep();
connect();
} catch (SocketException e) {
System.err.println("ERROR :: FTP Server Unreachable");
sleep();
connect();
} catch (IOException e) {
System.err.println("ERROR :: FTP Server Unreachable");
sleep();
connect();
}
}
public void sleep(){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
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;
}
}
}
您是否尝试更改代码?@Mohammod Hossain您的代码很好,但我想知道是否有更好的方法来测试连接,而不需要实际尝试连接。我认为您正在使用org.apache.commons.net.ftp库,所以API对连接到ftp服务器有这样的实现。您得到您想要的答案了吗?@Mohammod Hossain,谢谢,我尝试了一种不同的方法看起来您使用的是org.apache.commons.net.ftp在这种情况下,您可以使用isAvailable()或isConnected()方法,它们的运行速度比ftpClient.sendNoOp()快。缺点是这两种方法仍然不能保证连接正常工作。