【发布时间】:2017-04-18 06:34:40
【问题描述】:
所以,我有一段代码连接到服务器并以 2mb 的块下载大约 2gb 的内容。所有这些都在一个线程中完成。有时我需要停止线程,因为主线程中发生了不同的错误,或者我想关闭应用程序。我的问题是我无法关闭连接的 InputStream。每次我调用 close() 方法时,InputStream 都会消耗服务器发送的整个 2gb。
有没有办法在不消耗服务器发送的整个内容的情况下关闭 InputStream?
fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
res.getEntity().getContent().close();
res.getEntity().getContent()返回从连接创建的 InputStream。
res 是一个 apache httpResponse。
fos 是我要将响应内容保存到的 FileOutputStream。
编辑:线程的运行方法
CHUNK_SIZE: int: 2mb in bytes
@Override
public void run() {
int expectedCode;
do{
try {
client = HttpClients.createDefault();
HttpGet req = new HttpGet(url.toString());
HttpResponse res = client.execute(req);
if (res.getStatusLine().getStatusCode() == 200) {
while(running){
fos.getChannel().transferFrom(Channels.newChannel(res.getEntity().getContent()), bytes_read, CHUNK_SIZE);
}
} else {
log.error(Languages.getString("Download.2") + expectedCode); //$NON-NLS-1$
}
} catch (Exception ex) {
log.error(ex);
} finally{
try{
rbc.close();
} catch(Exception ex){
log.error(ex);
}
}
}while(!isFinished() && running);
try{
rbc.close();
fos.close();
client.close();
} catch(Exception ex){
log.error(ex);
}
}
【问题讨论】:
-
所以每当你调用 .close() 时,线程都会被阻塞,直到所有 2Gb 的数据都被传输完?
-
.close() 方法阻塞线程并接收直到所有 2gb 都被读取但它不传输任何字节它只清除输入流
-
也许,.close() 不是罪魁祸首,而是它周围的代码。 InputStream 的实际实现是什么?你能发布一些附加代码吗?