我打开我的程序开始到FTP服务器的连接。
之前,我在服务器上执行操作,我要检查,如果连接成功建立。 最简单快速的方式,所以如果连接走了,我会尝试重新连接。
我用这个代码来做到这一点:
private boolean checkConnection()
{
try
{
boolean success = ftpClient.login(user_name, password);
if(success)
return true;
else
return false;
}
}
但这种方法抛出一个空指针异常,当连接被关闭。
我可以检查与连接ftpClient.connect(server, port);
但就是喜欢attampting遍布重新连接。
什么是BES的检查方法有什么联系?
试图发送一个简单的sendNoOp()
和检查的答复可能是轻微检查connecion一个好办法:
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;
}
}
}
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();
}
}