FTPClient download file, program suspended animation problem

【Symptom】
In the past two days, FTP download has been used in the java project. The code is written like the previous project, but after clicking download, the program is debugged to the following line, and there is no response.
InputStream ins = ftpClient.retrieveFileStream(filePath);
It doesn't matter if there is no response, click download again, the code will not go to this method at all, unless the service is restarted, debugging is extremely painful.
 
I thought it was a folder location error, I just wanted to see if I could get the file list in the directory
FTPFile[] fs = ftpClient.listFiles();
As a result, there is no news when the program reaches this stage. . .
 
【Solution】
Before calling the FTPClient.listFiles() or FTPClient.retrieveFile() method, call FTPClient.enterLocalPassiveMode() first
 
【Test example】
Example 1:
ftpClient.enterLocalPassiveMode();
FTPFile[] fs = ftpClient.listFiles();

Example 2:

ftpClient.enterLocalPassiveMode();
InputStream ins = ftpClient.retrieveFileStream(remotefilePath);

Example 3:

ftpClient.enterLocalPassiveMode();
InputStream ins = ftpClient.retrieveFile(remotefilePath, outputStream);

【Cause Analysis】

FTP has two modes: active mode (active mode) and passive mode (passive mode), the default is active mode enabled.
Because FTP is a TCP link, when reading a file, a three-way handshake is required
 
When I am debugging here, the firewall of the FTP server is turned off, but the client is running locally, and the firewall of my server is turned on.
Therefore, when FTP uses the active mode, after the three-way handshake, the FTP Server will actively initiate a data connection request to the FTP Client.
At this time, due to the restriction of the firewall, the requested port may be blocked in the TP Client, and the data stream sent by the FTP Server cannot be received normally, so the phenomenon of suspended animation will occur.
 
If the FTP is forced to use passive mode, after the three-way handshake is completed, the client TP Client will ask the Server to open a port, and passively wait for the TP Client to establish a file transfer link.
At this point, the client TP Client can get the data normally.
 
For more information on active mode and passive mode, see the following blogs:
 
【Extended question】
If your program can download FTP files normally on your computer, but it can't be done after going online, the downloaded file will be suspended.
Please check if the firewall of the production server is not closed
If there are special reasons, the production server firewall should be open
It is recommended to use FTPClient.enterLocalPassiveMode() when writing Java code to read files;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727800&siteId=291194637