FtpClient一定要setSotimeOut、setDataTimeout
SotimeOut,简单说就是读取数据时阻塞链路的超时时间。
/**
* Enable/disable {@link SocketOptions#SO_TIMEOUT SO_TIMEOUT}
* with the specified timeout, in milliseconds. With this option set
* to a non-zero timeout, a read() call on the InputStream associated with
* this Socket will block for only this amount of time. If the timeout
* expires, a <B>java.net.SocketTimeoutException</B> is raised, though the
* Socket is still valid. The option <B>must</B> be enabled
* prior to entering the blocking operation to have effect. The
* timeout must be {@code > 0}.
* A timeout of zero is interpreted as an infinite timeout.
* (设置一个超时时间,用来当这个 Socket 调用了 read() 从 InputStream 输入流中
* 读取数据的过程中,如果线程进入了阻塞状态,那么这次阻塞的过程耗费的时间如果
* 超过了设置的超时时间,就会抛出一个 SocketTimeoutException 异常,但只是将
* 线程从读数据这个过程中断掉,并不影响 Socket 的后续使用。
* 如果超时时间为0,表示无限长。)
* (注意,并不是读取输入流的整个过程的超时时间,而仅仅是每一次进入阻塞等待输入流中
* 有数据可读的超时时间)
* @param timeout the specified timeout, in milliseconds.
* @exception SocketException if there is an error
* in the underlying protocol, such as a TCP error.
* @since JDK 1.1
* @see #getSoTimeout()
*/
public synchronized void setSoTimeout(int timeout) throws SocketException {
//.....
}
/**
* Sets the timeout in milliseconds to use when reading from the
* data connection. This timeout will be set immediately after
* opening the data connection, provided that the value is ≥ 0.
* <p>
* <b>Note:</b> the timeout will also be applied when calling accept()
* whilst establishing an active local data connection.
* @param timeout The default timeout in milliseconds that is used when
* opening a data connection socket. The value 0 means an infinite timeout.
*/
public void setDataTimeout(int timeout)
{
__dataTimeout = timeout;
}
如果不设置,可能会在网络波动时阻塞,至此无限时阻塞在此!!!
所以使用ftp时,一般需要设置timeout来保证程序正常运行(不卡死)。
FTPClient ftpClient = null;
try {
ftpClient = new FTPClient();
ftpClient.setDefaultTimeout(10000);
ftpClient.setConnectTimeout(10000);
ftpClient.setDataTimeout(10000);
// 连接FTP服务器
ftpClient.connect(host, port);
// 登陆FTP服务器
ftpClient.login(userName, password);
// 中文支持
ftpClient.setControlEncoding("UTF-8");
// 设置文件类型为二进制(如果从FTP下载或上传的文件是压缩文件的时候,不进行该设置可能会导致获取的压缩文件解压失败)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 主动模式
//ftpClient.enterLocalActiveMode();
// 被动模式 每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据 防止假卡死
ftpClient.enterLocalPassiveMode();
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.error("连接FTP失败");
ftpClient.disconnect();
} else {
ftpClient.setSoTimeout(10000);
logger.info("FTP连接成功!");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("登陆FTP失败,请检查FTP相关配置信息是否正确!", e);
}
return ftpClient;