2016-11-30 143 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