Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

calculating roundtrip time for a http connection and socket for google etc

Hi,
I have a following piece of code which create an http connection to www.google.com :
 HttpURLConnection conn = null;
        boolean success = true;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestProperty("Connection", "close");
            conn.setConnectTimeout(50); //

            // put itmestamp here
            conn.connect();
            System.out.println("read timeout = "+conn.getReadTimeout());
            System.out.println("connectTimeout = " + conn.getConnectTimeout());

Open in new window


Here i have set connect time out manually. How do i find out exactly how much time it takes to connect.
Also i want to send some request data and receive response to calculate exactly how much time a rountrip takes.

How do i do it ?

Also same thing i want to do on a socket for which i have the following code :
SocketAddress sockaddr = new InetSocketAddress("www.google.com", 80);
        Socket socket = new Socket();
        socket.connect(sockaddr, 50);

        System.out.println("is socket connected = " + socket.isConnected());
        System.out.println("socket timeout = "+socket.getSoTimeout());
        socket.close();

Open in new window


But again here i want to send something on the socket and receive some result like a ping so as to know how much time it took.
thanks
Avatar of dpearson
dpearson

Record the time before you connect and check it after you connect:

            long timeBeforeConnect = System.currentTimeMillis() ;
            conn.connect();
            long elapsed = System.currentTimeMillis()  - start ;

Elapsed is how long it took to make the connection in milliseconds.  If it times out it'll be the time it took to timeout.

Same for the socket.

If you want to measure the roundtrip time to send some data over the pipe and get a response you can use the same pattern.  Record the time before you send the request.  Then check the time when you get the response - the difference is how long it took to do the roundtrip.

Doug
Avatar of Rohit Bajaj

ASKER

Hi
What request should i send over socket to calculat roundtrip time ? Plz give me an example for google.
ASKER CERTIFIED SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial