Nate
Nate

Reputation: 837

count the number of bytes that java web client sends and receives

I have Simple web client written on Java and I have to count the number of bytes that it sends and recieves. Then I have to compare results with netstat -s command. Also, how can i measure average size of the packets I sent and receive. Here is 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();
        }

    }
}

Upvotes: 0

Views: 742

Answers (1)

Serge
Serge

Reputation: 6095

You could create your own implementations of FilterInputStream and FilterOutputStream that will count all data passed through. Then just use them as filters, for example:

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

Upvotes: 2

Related Questions