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

时间:2016-11-30 13:19:38

标签: java sockets stream file-transfer

如何使用套接字计算下载的数据量和要下载的总数据。

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

请提出建议,并提前致谢。

1 个答案:

答案 0 :(得分: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