mervyn.777
mervyn.777

Reputation: 107

Incomplete UDP Packet received

I'm facing a very weird problem with receiving data using UDP in Android. I'm writing an application to control a wifi module from an android device. I'm able to successfully send data to this remote wifi device. But I'm not able to receive 'complete' data packet from this wifi device.

My code in android is:

public static void receivePacket(int receiverPort, Context context) {
    DatagramSocket socket = null;
    String text = "";
    try {           
        byte[] message = new byte[1500];
        DatagramPacket packet = new DatagramPacket(message, message.length);
        socket = new DatagramSocket(receiverPort);          
        //socket.setSoTimeout(5000);
        for (int i = 0; i < 12; i++) {
            socket.receive(packet);
            text += new String(message, 0, packet.getLength()) + "\n";
        }
        socket.close();
        Log.d("Received Message", text);
    } catch (Exception e) {
        Log.e("UDP", "S: Error", e);
    } finally {
        if(null != socket){
            socket.close();
        }
    }
}

So if I'm expecting the data "$BEG1;$PID2;$PIP192.168.15.245;$PPN80;$DAT987654321;$END1;" I'm only getting "$BEG1;$PID2;$PIP192.168.15.245;$PPN80;$DAT98"

I tried to use UDP WinChat application to see if it's able to get the message from the wifi module and I'm able to get the entire data.

Also if i try sending a really long message to the android device using UDP Win Chat Application I'm able to get the entire data!

I'm totally confused! Please Help.


I was able to isolate the problem. (Still havent found the fix though :(...)

From the above code I'm making use of the same packet.getLength() for every iteration assuming that it will change each time according to the data it has received. But sadly that's not the expected behavior. The getLength() makes use of the previous value and truncates the newly arrived messages. [Please note: This is a random behavior and doesn't happen all the time]

Now the question is, how do I change or refresh this attribute everytime I receive a new message within the loop?

Upvotes: 1

Views: 2595

Answers (1)

user207421
user207421

Reputation: 311039

You need to reset the DatagramPacket length before every receive. Otherwise it keeps shrinking to the smallest packet received so far.

Upvotes: 4

Related Questions