0
votes

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
UDP is not a lossless protocol, use TCP.. it checks whether the packet was received and also it's integrity with an 32bit CRC - Bojan Kseneman
The protocol that I work with is UDP protocol. No chance to choose. Thanks. - Niaz
Ok, but you cannot be certain that a packet will be received. That is the difference between UDP and TCP. UDP is faster because you don't check if a packet was received. TCP has that handled including when a packet is malformed (CRC error) - Bojan Kseneman

1 Answers

0
votes

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()));
}