2016-11-30 4 views
1

ダウンロードしたデータの量とソケットを使用してダウンロードする合計データを計算する方法。ダウンロードするファイルサイズとダウンロードする合計データを計算する方法

E.G. 500kb/95000kb ... 95000kb/95000kb

ここに私のコードを参考にしました。

private static void updateFile() { 
    Socket socket = null; 
    PrintWriter writer = null; 
    BufferedInputStream inStream = null; 
    BufferedOutputStream outStream = null; 

    try { 
     String serverName = System.getProperty("server.name"); 

     socket = new Socket(serverName, 80); 
     writer = new PrintWriter(socket.getOutputStream(), true); 
     inStream = new BufferedInputStream(socket.getInputStream()); 
     outStream = new BufferedOutputStream(new FileOutputStream(new File("XXX.txt"))); 

     // send an HTTP request 
     System.out.println("Sending HTTP request to " + serverName); 

     writer.println("GET /server/source/path/XXX.txt HTTP/1.1"); 
     writer.println("Host: " + serverName + ":80"); 
     writer.println("Connection: Close"); 
     writer.println(); 
     writer.println(); 

     // process response 
     int len = 0; 
     byte[] bBuf = new byte[8096]; 
     int count = 0; 

     while ((len = inStream.read(bBuf)) > 0) { 
      outStream.write(bBuf, 0, len); 
      count += len; 
     } 
    } 
    catch (Exception e) { 
     System.out.println("Error in update(): " + e); 
     throw new RuntimeException(e.toString()); 
    } 
    finally { 
     if (writer != null) { 
      writer.close(); 
     } 
     if (outStream != null) { 
      try { outStream.flush(); outStream.close(); } catch (IOException ignored) {ignored.printStackTrace();} 
     } 
     if (inStream != null) { 
      try { inStream.close(); } catch (IOException ignored) {ignored.printStackTrace();} 
     } 
     if (socket != null) { 
      try { socket.close(); } catch (IOException ignored) {ignored.printStackTrace();} 
     } 
    } 
} 

これを達成するため、事前に感謝してください。

+0

直接にはできません。ファイルをダウンロードしようとすると。私はあなたがHttpURLConnectionのようなクラスを使用することをお勧めします:connection.getContentLength()ダウンロードするデータの合計サイズを知るために。ソケットを使用することは可能ですが、最初にコンテンツのヘッダが必要で、 "content-length"の値を得る例 – toto

+0

HTTPの行終端文字は 'println()'が与えるものではなく '\ r \ n'です。ビルトインされているサードパーティ製のクライアントと任意の数のサードパーティ製のクライアントがある場合は、HTTPを自分で実装しないでください。それは自明ではない。理由については、RFC 2616を参照してください。 – EJP

答えて

1

一般に、ソケットは受信データのサイズを知らない。ソケットはTCP接続にバインドされ、TCPはデータサイズに関する情報を提供しません。それはアプリケーションプロトコルのためのタスクであり、あなたの例ではHTTPです。

HTTPは、ヘッダーのデータサイズを示します。 HTTP応答は次のようになります。

HTTP/1.1 200 OK 
Content-Type: text/html; charset=utf-8 
Content-Length: 13 
Connection: keep-alive 

<html></html> 

HTML応答にはヘッダーと本文が含まれています。本文は改行でヘッダから区切られています。 Content-Lengthヘッダーには、本文のサイズがバイト単位で格納されます。

したがって、ヘッダーを解析して長さを見つけたり、java.net.HttpURLConnectionのような既存のクラスを使用したりすることができます。

関連する問題