简体   繁体   中英

UDP Datagram packet receive loop delay

I'm running a Thread with a an active loop waiting for UDP packets.

When message is received , I want to process it.

I need to receive several packets per second (~20).

I'm taking a minimalist example, just logging after receiving UDP packet

while (socketUDP != null) {
    message = new byte[6];
    packet = new DatagramPacket(message, message.length);

    try {
        socketUDP.receive(packet);
        command = new String (message, 0, packet.getLength());
    } catch (IOException e) {
        Log.e(LOG_TAG, LOG_TAG + " IOException: " + e.getMessage() );
    }

    Log.d(LOG_TAG, "test");
}

The behaviour is weird, because, for example, I send 50 UDP packets in 1 second, no one is lost, and Android take's about 3/4 seconds to show the 50 log text message "test"!!

So, it seems that Android's VM is saving somewhere all packets in a buffer and process it when possible!

I need to process datagram's packets as soon as possible in Android.

It seems I'm missing something.

Any ideia wich is the best way to do that?!

If you're in a hurry, then:

  • create all your objects before listening of UDP
  • log after you're done receiving all your packets, or at least log a minimal amount, and infrequently.

Right now, every single time a packet arrives, you create a DatagramPacket and a String, and then Log.e, all of which should take much more time than receiving the packet itself. Of course, even when optimized, there's no real-time guarantee of delivery.

Try to ping device which is sending packets. It helps me. For example I'm using this code before receiving packets:

pingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Runtime runtime = Runtime.getRuntime();
            try {
                // Ping 10 times at 169.254.169.168
                runtime.exec("/system/bin/ping -c 10 169.254.169.168");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    pingThread.start();

After that you can call:

socketUDP.receive(packet);

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