apache commons ftp客户端超时问题
问题描述:
我正在从一个Apache库(commons.net ver 3.2)的帮助下从服务器上下载ftp文件。下载很好,我收到了我需要的所有文件并将它们保存在一个文件夹中。我遇到的问题是超时,因为当我下载时连接中断,我需要一个错误消息,告诉我连接已经丢失,但是我发现这样做有困难,我搜索了无数的论坛,包括这个一个和我已经尝试了很多方法来解决这个问题,但没有人有结果呢!那我的代码如下:apache commons ftp客户端超时问题
public void doSomething(String ip, int port, String user, String pass, String server, String remotePath, String localPath) {
int tenseconds = 10 * 1000;
int thirtyseconds = 30 * 3000;
Socket s4 = new Socket();
java.net.InetSocketAddress adr = new java.net.InetSocketAddress("213.0.17.234", 21);
s4.connect(adr, thirtyseconds);
FTPClient client = new FTPClient();
org.apache.commons.vfs2.FileSystemOptions fileSystemOptions = null;
String key = FtpFileSystemConfigBuilder.getInstance().getEntryParser(fileSystemOptions);
try {
client.setConnectTimeout(tenseconds);
client.setDefaultTimeout(thirtyseconds);
client.connect(ip, port);
client.setSoTimeout(thirtyseconds);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new FileSystemException("vfs.provider.ftp/connect-rejected.error");
}
client.enterLocalPassiveMode();
boolean login = client.login(user, pass);
URL url = new URL("ftp://" + user + ":" + pass + "@" + server + remotePath + ";type=i");
URLConnection urlc = url.openConnection();
urlc.setConnectTimeout(1000);
InputStream is = urlc.getInputStream();
BufferedWriter bw = new BufferedWriter(new FileWriter(localPath));
int c;
client.setSoTimeout(tenseconds);
client.setControlKeepAliveTimeout(10000);
while ((c = is.read()) != -1) {
urlc.getConnectTimeout();
bw.write(c);
}
long t2 = System.currentTimeMillis();
System.out.println(t2);
JOptionPane.showMessageDialog(null, "se cargo el primer fichero!", "información", JOptionPane.INFORMATION_MESSAGE);
if (login) {
FTPFile[] files = client.listFiles();
for (FTPFile file : files) {
if (file.getType() == FTPFile.DIRECTORY_TYPE) {
System.out.println("ftp file: " + file.getName() + ";" + FileUtils.byteCountToDisplaySize(file.getSize()));
} else if (file.getType() == FTPFile.FILE_TYPE) {
System.out.println("ftp file: " + file.getName() + ";" + FileUtils.byteCountToDisplaySize(file.getSize()));
}
}
is.close();
bw.close();
client.setSoTimeout(tenseconds);
client.logout();
client.disconnect();
}
} catch (IOException e) {
StringWriter sw0 = new StringWriter();
PrintWriter p0 = new PrintWriter(sw0, true);
e.printStackTrace(p0);
System.out.println("connection probably lost");
JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
我已经尝试了所有的东西可以找到一个已经阅读了setdefaulttimeout用来激活所有的超时,connectiontiomeout来等待连接和getsotimeouts使用当我们下载一个文件但它不起作用时,我已经尝试了5秒钟,所以它不会下载文件,但它不起作用,我已经读过,有一些问题whit connectiontimeouts,我们应该使用socketfactory,所以我也修了一个套接字工厂,我尝试了,但它不起作用,而且我已经达到了一点,我有点绝望,所以我要求你的帮助,我都尝试client.setControlKeepAliveTimeout(10000);
建立一个活动超时但它没有工作! :(
答
有你重新连接到服务器与一个URLConnection你已经与FTPClient连接后的任何原因?
FTPClient有retrieveFileStream方法。如果过程中出现错误,将抛出一个异常处理
'setControlKeepAliveTimeout'的参数以秒为单位。 – 2013-07-18 15:04:13