Вопрос

I have a Java application that is receiving UDP packets in a loop:

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

When I get packets, many of them arrive as expected, but every once in a while, I get a packet that is broken up into two pieces:

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

As you can see on lines 4 and 5, the last trailing characters of 4 have been cut off and a new packet of the remaining characters have arrived. From my reading about UDP, everyone warns that UDP does not guarantee the arrival of packets. In my case that is not a problem; a dropped packet hear or there isn't going to break my application. However, I haven't found anything about packets not necessarily arriving as complete. In fact, I have read that this does not happen.

How is this dealt with usually? It is difficult for me to know if a packet that has arrived is complete or not in which I could just wait for the next packet and append the data.

Это было полезно?

Решение

What you describe is impossible. UDP datagrams arrive intact and complete or not at all. The server must be sending the data in two datagrams.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top