我正在研究一个项目,它将在修改后将一些文件上传到FTP服务器......除了上传文件外,我还有其他所有文件。我可以成功连接到FTP服务器,但是一旦文件上传,程序会挂起几分钟,然后它会说它超时了。
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:762)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:565)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:557)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1795)
at AdvertisementCreator.main(AdvertisementCreator.java:128)
e
这是我为FTP连接的代码:(请记住,我省略了登录详细信息)
FTPClient fClient = new FTPClient();
try {
fClient.connect(server, port);
showServerReply(fClient);
int replyCode = fClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = fClient.login(user, pass);
showServerReply(fClient);
if (!success) {
System.out.println("Could not login to the server");
} else {
System.out.println("You are now logged on!");
loginLoop = false;
}
fClient.enterLocalPassiveMode();
fClient.setFileType(FTP.BINARY_FILE_TYPE);
File localFile = new File("files\\shared.txt");
String remoteFile = "shared.txt";
InputStream inputStream = new FileInputStream(localFile);
System.out.println("Start uploading the file");
boolean done = fClient.storeFile(remoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println(remoteFile+" has been uploaded successfully");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}finally {
try {
if (fClient.isConnected()) {
fClient.logout();
fClient.disconnect();
System.out.println("FTP Disconnected");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
直到今天我还没有真正搞过Apache Commons FTP。如果有人能提供一些见解,我将非常感激
编辑:我忘了提到在添加以下行之前,文件已传输,但当我尝试在服务器上打开它时,它是空的。
fClient.enterLocalPassiveMode();
fClient.setFileType(FTP.BINARY_FILE_TYPE);
这是您必须首先调试的常见连接问题:
首先,确保正确键入服务器的名称。还要确保您已正确指定端口(如果由于某种原因,它不是众所周知的FTP端口21)。
然后,确保本地主机和远程FTP服务器之间具有TCP连接:例如,打开命令shell并尝试执行“telnet 21”。
java -Dftp.socksProxyHost=<proxy host> -Dftp.socksProxyPort=<proxy port> -Djava.net.socks.username=<proxy username> -Djava.net.socks.password=<proxy user password> -classpath ... MainClass
查看Java中的所有networking properties。
而另一种可能性是你有一些本地防火墙阻止这种连接。检查并阅读防火墙手册。