简体   繁体   English

在Android上丢失UDP套接字数据包

[英]Losing UDP socket packets on Android

I'm facing UDP packet loss problem based on Android devices. 我面临基于Android设备的UDP数据包丢失问题。 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. 在此解决方案中,建议将数据报套接字大小设置为64k。 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

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 被选中的anwser的作者似乎在使用过去时时遇到了问题,并且几乎可以一直说话,但有时他会说

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 . 顺便说一句,设置缓冲区大小的方法可能可行,实际上日志消息会根据您的平台缓冲区大小做出响应,直到您无法更改为止,请参阅Android DatagramSocket接收缓冲区大小

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM