2016-11-30 97 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中的行終止符是'\ r \ n',而不是'println()'可能給您帶來的任何內容。當內置支持和任意數量的第三方客戶端時,請勿自行實施HTTP。這是不平凡的。有關原因,請參閱RFC 2616。 – EJP

回答

1

套接字通常不知道接收數據的大小。套接字綁定到TCP連接,並且TCP不提供有關數據大小的任何信息。這是應用程序協議的任務,在您的示例中它是HTTP。

HTTP指示Content-Length標題中的數據大小。 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