如何计算下载的文件大小和要下载的总数据量

How to calculate the downloaded file size and total data to be downloaded

如何使用socket计算下载数据量和总下载数据量。

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();}
        }
    }
}

请提出建议以实现此目的并提前致谢。

套接字一般不知道接收数据的大小。套接字绑定到 TCP 连接,TCP 不提供有关数据大小的任何信息。它是应用程序协议的任务,在您的示例中是 HTTP。

HTTP表示Content-Lengthheader中的数据大小。 HTTP 响应如下所示:

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

<html></html>

HTML 响应包含 header 和 body。 body 与 header 之间用换行符分隔。 Content-Length header 包含 body 的字节大小。

所以您可以解析 header 并找到长度,或者使用现有的 class,例如 java.net.HttpURLConnection