我有一个在循环中接收UDP数据包的Java应用程序:
while (running) {
try {
// Block until a packet is received on the port
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
serverSocket.receive(receivePacket);
ByteArrayInputStream byteIn = new ByteArrayInputStream(receivePacket.getData(), 0, receivePacket.getLength());
DataInputStream dataIn = new DataInputStream(byteIn);
// Print packet
String packetString = "";
while((packetString = dataIn.readLine()) != null) {
Log.d("WiFi", packetString);
}
} catch (IOException ex) {
Log.d("WiFi", "Problem receiving: " + ex.toString());
}
}
当我收到数据包时,其中许多数据包按预期到达,但每隔一段时间,我就得到一个分为两部分的数据包:
103, -5.84, 5.64, 140.72, #A-=-22.53,-50.18,248.83, #G-=52.00,-69.00,-18.00, #M-=-146.66,-155.18,151.06, 2575012
103, -6.51, 5.62, 140.41, #A-=-22.53,-51.20,248.83, #G-=23.00,44.00,-7.00, #M-=-146.21,-156.13,151.06, 2575036
103, -7.23, 5.65, 140.09, #A-=-19.46,-49.15,243.71, #G-=17.00,68.00,-2.00, #M-=-144.85,-155.18,151.06, 2575063
103, -7.76, 5.60, 139.81, #A-=-17.41,-50.18,240.64, #G-=17.00,71.00,0.00, #M-=-143.94,-155.65,153
.47, 2575090
103, -8.51, 5.34, 139.40, #A-=-12.29,-47.10,233.47, #G-=31.00,-1.00,-5.00, #M-=-144.85,-154.70,151.87, 2575135
103, -9.20, 4.76, 138.95, #A-=-15.36,-50.18,239.62, #G-=22.00,30.00,-3.00, #M-=-146.66,-156.13,151.87, 2575200
103, -9.82, 4.46, 138.61, #A-=-15.36,-47.10,239.62, #G-=33.00,1.00,-3.00, #M-=-145.76,-156.13,152.27, 2575266
103, -10.38, 4.07, 138.23, #A-=-14.34,-48.13,235.52, #G-=30.00,4.00,-7.00, #M-=-144.85,-155.65,152.27, 2575372
103, -10.90, 3.76, 137.90, #A-=-14.34,-48.13,237.57, #G-=29.00,19.00,-4.00, #M-=-145.30,-156.13,151.47, 2575520
103, -11.41, 3.53, 137.44, #A-=-15.36,-48.13,235.52, #G-=25.00,18.00,-4.00, #M-=-146.21,-155.18,151.47, 2576917
正如您在第4行和第5行所看到的,最后的4个尾随字符已被切断,剩余字符的新数据包已到达。从我对UDP的阅读中,每个人都警告说UDP并不能保证数据包的到达。在我的情况下,这不是一个问题;丢失的数据包听到或者不会破坏我的应用程序。但是,我没有发现任何关于数据包不一定到达的完整信息。事实上,我已经读过这个不会发生。
通常如何处理?我很难知道到达的数据包是否完整,我可以等待下一个数据包并附加数据。
答案 0 :(得分:0)
你描述的是不可能的。 UDP数据报完好无损地完成或完全到达。服务器必须以两个数据报发送数据。