简体   繁体   中英

DatagramSocket send blocks on Android 7.0

I'm using a DatagramSocket in an Android app for some UDP communication with a server. It sends packets to the server and listens for packets from the server. This was created about four years ago and has been working fine. A customer recently upgraded a tablet to Android 7.0 and now DatagramSocket.send(DatagramPacket) blocks indefinitely without sending anything.

I've tried the below test code to demonstrate the problem. On all Android versions up to at least 6.0.1, the below code works as expected. The receive method, running in a separate thread, blocks waiting for a packet. The send method completes immediately and execution continues. If I run this on 7.0, the send method blocks and nothing is sent.

I'm not getting any security exceptions. I've been trying to find documentation describing a relevant change to Android or DatagramSocket but have yet to find anything. If I don't call the receive method, the send method doesn't block.

I've tried working around this using two DatagramSocket instances: one sending, one receiving. But the responses from the server need to come back on the same port and I don't see a way I could achieve this with two sockets.

So my questions are, why is this now happening? Is there something new I now need to do in Android 7.0? Or, is there another way I could work around this?

try {
    final DatagramSocket socket = DatagramChannel.open().socket();
    socket.bind(null);
    DatagramPacket packet = new DatagramPacket(new byte[100], 100, new InetSocketAddress("my.server.com", 31000));
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                DatagramPacket receivedPacket = new DatagramPacket(new byte[100], 100);
                socket.receive(receivedPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
    Thread.sleep(1000);
    socket.send(packet);
    socket.close();
} catch (Exception e) {
    e.printStackTrace();
}

With a bit of trial and error, I finally fixed this issue with the below code change. I'm not sure what has changed in DatagramChannel in Android 7 but I didn't really need it anyway.

//final DatagramSocket socket = DatagramChannel.open().socket();
//socket.bind(null);
final DatagramSocket socket = new DatagramSocket();

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