简体   繁体   中英

Java DatagramSocket receive() takes more time than send() for the same packet size

I am writing a UDP datagram Server-Client application in which packets of size either 60/100/200 bytes (including UDP+IP+MAC header) are transmitted over high-speed link. This application is latency critical ie each packet should experience the same latency, ideally the round-trip time over the link. However, as packet size increases, a proportional increase in the latency is acceptable.

To this end, I have measured block by block execution time of my code. Strangely, I have observed that, time taken by socket.receive(pkt) is in order of 400-500 microseconds and keeps increasing as the packet size increases. On the other hand, socket. send (pkt) takes 20-100 microseconds. Thus, socket.receive() packet on client and server is causing more than 1 millisecond latency over the actual round-trip time.

Note that, both Server-Client sockets are able to handle the high packet arrival rates and packet loss is not a concern.

I clearly fail to understand, why such a behavior only on receive() function if the packet size is same? Help/discussion is highly appreciated.

Following is the block of code for receiving datagram packets.

private void receive() throws Exception {
    receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
    while(true){
        long t1 = System.nanoTime();
        clientSocket.receive(receivedPacket);
        System.out.println("time to receive "+ TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - t1));
        threadPool.execute(new ClientSend(new DatagramPacket(receivedPacket.getData(), receivedPacket.getLength(), serverAddress, receiverPort)));
    }
}

A send is usually just a transfer into the socket send buffer. The actual sending over the wire is asynchronous. You aren't measuring that.

A receive consists first of blocking if necessary until data is available in the socket receive buffer, then a transfer out of the receive buffer.

They aren't comparable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM