파일을 더 빠르게 다운로드하려면 아래 코드에 여러 연결을 추가하고 싶습니다. 누군가 나를 도울 수 있습니까? 미리 감사드립니다.Java 다중 연결로 파일 다운로드
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
더 기본적인 질문 : 왜 다중 연결을 추가하면 더 빨리 다운로드 할 수 있다고 생각합니까? 서버가 처리량을 능동적으로 조절하지 않는 한 이미 전체 파이프에 가깝게 사용할 것입니다. – Anon
@Anon : 그건 일반적인 트릭입니다. 서버에 대한 RTT가 파이프를 가득 채울 수 없을 정도로 더 많은 연결을하는 데 도움이됩니다 (최대 대역폭은 RTT 당 하나의 수신자 창이됩니다). 또한 TCP는 각 연결에 공평한 분배를 시도하기 때문에 어딘가에서 정체가 발생하는 경우에도 도움이됩니다. 더 많은 연결, 더 많은 공유, 더 많은 대역폭. 그러나 연결 수에 따라 선형 증분이 발생하지는 않습니다. – PypeBros