2010-04-23 7 views
1

파일을 더 빠르게 다운로드하려면 아래 코드에 여러 연결을 추가하고 싶습니다. 누군가 나를 도울 수 있습니까? 미리 감사드립니다.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) { 
      } 
     } 
    } 
} 
+0

이미 가지고있는 코드를 이해하고 있습니까? 이것은 매우 독립적 인 것으로 보이기 때문에 여러 인스턴스를 만들어 스레드 풀에 전달해야합니다. – Anon

+0

더 기본적인 질문 : 왜 다중 연결을 추가하면 더 빨리 다운로드 할 수 있다고 생각합니까? 서버가 처리량을 능동적으로 조절하지 않는 한 이미 전체 파이프에 가깝게 사용할 것입니다. – Anon

+1

@Anon : 그건 일반적인 트릭입니다. 서버에 대한 RTT가 파이프를 가득 채울 수 없을 정도로 더 많은 연결을하는 데 도움이됩니다 (최대 대역폭은 RTT 당 하나의 수신자 창이됩니다). 또한 TCP는 각 연결에 공평한 분배를 시도하기 때문에 어딘가에서 정체가 발생하는 경우에도 도움이됩니다. 더 많은 연결, 더 많은 공유, 더 많은 대역폭. 그러나 연결 수에 따라 선형 증분이 발생하지는 않습니다. – PypeBros

답변

1

스레드를 사용할 수 있습니다.

Thread/Runnable에 RandomAccessFile을 다운로드하고 업데이트하기위한 코드를 입력하고 여러 인스턴스를 시작하십시오.

전역 카운터 (동기화 된 액세스)를 사용하여 다운로드가 완료된 스레드 수를 추적하고 파일을 닫기 전에 모든 스레드가 카운터를 늘릴 때까지 주 스레드를 대기시킵니다.

스레드 A가 seek(somePosition)을 호출 할 수 없도록 스레드 A가 파일의 다른 부분에 쓰는 동안 RandomAccessFile에 대한 모든 액세스를 동기화해야합니다.

+2

하나의'RandomAccessFile'에서 동기화하는 대신 각 스레드에 고유 한 파일을 제공하고 OS가 디스크 버퍼에서 동기화를 관리하도록합니다. – Anon

0

당신이 무엇을 생각해 냈는지 확인하십시오. 여러 스레드의 오버 헤드와 스레드 간의 조정으로 인해 코드가 느려질 수 있습니다. 병목 현상이 확실하지 않으면 코드 복잡성이 증가하고 디버깅하는 것이 중요하지 않은 경우에만이 작업을 수행하십시오.