Android UDP server does not receive packets

2019-09-09 20:29发布

问题:

I have the following code to receive UDP packets:

public class AsyncReceiveUdp2 extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... f_url) {
    int udp=111;
    byte[] packet = new byte[2000];
    DatagramPacket dp = new DatagramPacket(packet, packet.length);
    DatagramSocket ds = null;
    try {
        ds = new DatagramSocket(udp);
        ds.receive(dp);
        //...
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ds != null) {
            ds.close();
        }
    }
    return null;
}

}

I send UDP data to computer from Android device. Computer immediately sends response as UDP packet. I save information to my log file on SD. And I see, that my app stays on the line "ds.receive(dp);" and does not run after it. I've tested on the Android device against a program on computer. As I understand it is tricky to receive UDP packets on Emulator. I could not do it. Redirect does not work for me as it is described here

Another important issue is to receive all packets, that were sent to the device. Lossless. How to modify the code for that?

Please help! Thanks!

回答1:

put your receive inside a while(true) loop. When you receive a packet call an if (pkg_received){break;}... or whatever you want to do... The problem is that you are probably only be receiving one package and you are getting timeout before receiving it.

Code edited and not tested

 while(true)
    {


        byte[] message = new byte[60*1024];
        DatagramPacket recv_packet = new DatagramPacket(message, message.length);


        try {
            socket.receive(recv_packet);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Log.d("UDP", "S: Receiving...listening on port " + recv_packet.getPort() );
        String rec_str;
        rec_str=new String(recv_packet.getData)

        Log.d("PACKAGE LENGTH",Integer.toString(recv_packet.getLength()));
}


标签: android udp