我正在尝试将文件上传到 FTP 服务器。
这是我的代码:
FTPClient ftpClient = new FTPClient();
try {
List<PoiCmsRule> appPois = getAllRules();
try (FileWriter writer = new FileWriter(backupFile)) {
new Gson().toJson(backupData, writer);
}
try (FileInputStream fis = new FileInputStream(backupFile)) {
ftpClient.connect(host);
ftpClient.login(login, password);
ftpClient.storeFile("backup.json", fis);
ftpClient.logout();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
当我在本地主机上运行它时,它工作得非常好。但是当我在服务器上运行时,我得到了这个异常:
Caused by: java.net.SocketException: Connection reset
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:186)
at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
我认为这表明我的防火墙或代理可能存在一些问题。
这是一个在 Ubuntu 服务器上运行的 Spring Boot 应用程序,并以 Nginx 作为代理。
如何找到导致此异常的原因?
<小时/>在被动模式下与命令行 ftp
成功连接的日志:
ubuntu@ip-server:~$ ftp -p -d my_host
Connected to my_host
220 FTP-Server
ftp: setsockopt: Bad file descriptor
Name (my_host): username
---> USER username
331 Please specify the password.
Password:
---> PASS XXXX
230 Login successful.
---> SYST
215 UNIX Type: L8
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls
ftp: setsockopt (ignored): Permission denied
---> PASV
227 Entering Passive Mode (153,92,207,128,127,65)
---> LIST
150 Here comes the directory listing.
// file list
226 Directory send OK.
ftp>
最佳答案
Apache Commons Net FTPClient
默认为 FTP 主动 模式。由于防火墙和 NAT 无处不在,主动模式现在几乎无法工作(有关详细信息,请参阅我关于 FTP active/passive connection modes 的文章)。
要将 FTPClient
切换到被动模式,请调用 FTPClient.enterLocalPassiveMode
之后 FTPClient.connect
的某处:
ftpClient.connect(host);
ftpClient.login(login, password);
ftpClient.enterLocalPassiveMode();
关于java - 套接字异常 : Connection reset while FTP upload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59046111/