java sockets - measuring time taken for send & response

Go To


I have a java program which sends a udp packet to a server when the user presses a button. The client then waits for a response from the server and aims to record the time in ms between when the udp packet was sent and when the response was received.

I'm having a problem whereby the timing does not seem to be accurate. It works fine most of the time giving a value of around 160ms (which is what I would expect). However, it sometimes enters a phase of giving values that are way to low (i.e. under 5ms).

I know the messages are being sent, as I can see the result appear on the server (and it is definitely more than a 1ms delay). This problem seems to occur if I spam the button many times.

My code is as follows:

public String sendMessage(String message){
    long startTime = System.currentTimeMillis();
    sendData = message.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        String returnString = new String(receivePacket.getData());
       //arg1 message, arg2 - transmit time
        addConsoleLine(returnString, System.currentTimeMillis() - startTime);
        return returnString;
    }catch (Exception e){
        return "error";
2012-04-04 03:24
by Adam Rogers


Its possible your transmits and receives are overlapping (either because your sendMessage() is being invoked from more than one thread, or, a packet was dropped.

i.e. You send the current request but receive the response from a previous request which will give the illusion of a very fast response time.

2012-04-04 03:41
by James Anderson
Ah, I think that seems very likely. Any ideas on how to get around this issue - Adam Rogers 2012-04-04 03:47
UDP is by definition "best effort" only. You must define your own protocol within the packet (i.e. sequence numbers) - Jim Garrison 2012-04-04 03:58
@Adam Rogers try putting the "send Time" in the message - James Anderson 2012-04-04 05:54
I think I'm slightly confused. If I press 'send' and get a 1ms response then I assume I'm getting the response from my previous 'send'. At that moment beforehand, I have more responses than sends - Adam Rogers 2012-04-04 14:05