Question

I'm facing UDP packet loss problem based on Android devices. I have two devices. Following code works correctly on one device. The other device lost many packages. I have already read solution of similar problem. In this solution, setting the datagram socket size to 64k is suggested. But I couldn't set it.

How can I change datagram buffer size?

My code:

DatagramSocket udpSocket = null;
try {
    udpSocket = new DatagramSocket(5004);
    udpSocket.setReceiveBufferSize(64*1024);
    Log.d("UDPSocket", "Buffer Size : " + udpSocket.getReceiveBufferSize());
} catch (SocketException e1) {
    e1.printStackTrace();
}

Log:

05-14 10:34:05.960: D/UDPSocket(28021): Buffer Size : 112640
Was it helpful?

Solution 2

I resolved my problem. I changed my receive data code.

Past code:

byte[] receiveData = new byte[1328];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
    udpSocket.receive(receivePacket);
} catch (IOException e) {
    e.printStackTrace();
}

New code:

ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.fromDatagramSocket(udpSocket);
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
FileInputStream fin = new FileInputStream(fileDescriptor);

byte[] receiveData = new byte[1328];
int readByte = fin.read(receiveData);

OTHER TIPS

Author of the chosen anwser seems to have problems using past tense and speak to present nearly all time, but at one point he exactly say

I removed this code setting buffer size and then it strated receving all the packets

So in fact it was changing datagram buffer size wich seems to have caused it's problem.

By the way, your method to set buffersize probably work, in fact log message respond to you with your platform buffer size, wich you can't change, see Android DatagramSocket receive buffer size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top