计算java Web客户端发送和接收的字节数

时间:2012-10-07 09:50:52

标签: java web network-programming client

我有使用Java编写的简单Web客户端,我必须计算它发送和接收的字节数。然后我必须将结果与netstat -s命令进行比较。另外,我如何测量发送和接收的数据包的平均大小。 这是WebClient.java:

package javaapplication1;

/**
 *
 * @author
 */
import java.net.*;
import java.io.*;
import java.util.*;

public class WebClient {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter host name (e.g., www.ouhk.edu.hk): ");
        String host = scanner.nextLine();
        System.out.print("Enter page (e.g., /index.html): ");
        String page = scanner.nextLine();
        final String CRLF = "\r\n"; // newline
        final int PORT = 80; // default port for HTTP

        try {
            Socket socket = new Socket(host, PORT);
            OutputStream os = socket.getOutputStream();
            InputStream is = socket.getInputStream();
            PrintWriter writer = new PrintWriter(os);
            writer.print("GET " + page + " HTTP/1.1" + CRLF);
            writer.print("Host: " + host + CRLF);
            writer.print(CRLF);
            writer.flush(); // flush any buffer
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null){
                            System.out.println(line);

            }
            System.out.println("Recieved bytes:");
            socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:2)

您可以创建自己的FilterInputStreamFilterOutputStream实现,这些实现将计算通过的所有数据。然后将它们用作过滤器,例如:

    OutputStream os = new CountingOutpurStream(socket.getOutputStream());
    InputStream is = new CountingInputStream(socket.getInputStream());