【发布时间】:2010-04-23 19:03:52
【问题描述】:
我想在下面的代码中添加多个连接,以便能够更快地下载文件。有人可以帮助我吗?提前致谢。
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it.
file = new RandomAccessFile("C:\\"+getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1) {
break;
}
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
}
}
}
}
【问题讨论】:
-
您了解您已有的代码吗?因为它看起来非常独立,您需要做的就是创建多个实例并将它们传递给线程池。
-
还有一个更基本的问题:为什么你认为添加多个连接会让你下载得更快?除非您的服务器正在主动限制吞吐量,否则您已经使用接近满的管道。
-
@Anon:这是一个常见的技巧。当与服务器的 RTT 无法保持管道满时,它有助于建立更多连接(无论带宽如何,每个 RTT 的最大接收器窗口为 1 个)。当您在某处遇到拥塞时,它也会有所帮助,因为 TCP 会尝试为每个 连接 分配公平的份额。更多连接,更多共享,更多带宽。但是,您不太可能随着连接数的增加而线性增加。
标签: java file connection download