简体   繁体   中英

How to obtain the actual packet size `byte[]` array in Java UDP

This is the subsequent question of my previous one: Java UDP send - receive packet one by one

As I indicated there, basically, I want to receive a packet one by one as it is via UDP.

Here's an example code:

ds = new DatagramSocket(localPort);
byte[] buffer1 = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer1, buffer1.length);

ds.receive(packet); 
Log.d("UDP-receiver",  packet.getLength() 
                             + " bytes of the actual packet received");

Here, the actual packet size is say, 300bytes, but the buffer1 is allocated as 1024 byte, and to me, it's something wrong with to deal with buffer1 .

How to obtain the actual packet size byte[] array from here?

and, more fundamentally, why do we need to preallocate the buffer size to receive UDP packet in Java like this? ( node.js doesn't do this )

Is there any way not to pre-allocate the buffer size and directly receive the UDP packet as it is?

Thanks for your thought.

You've answered your own question. packet.getLength() returns the actual number of bytes in the received datagram. So, you just have to use buffer[] from index 0 to index packet.getLength()-1.

Note that this means that if you're calling receive() in a loop, you have to recreate the DatagramPacket each time around the loop, or reset its length to the maximum before the receive. Otherwise getLength() keeps shrinking to the size of the smallest datagram received so far.

self answer. I did as follows:

int len = 1024;
byte[] buffer2 = new byte[len];
DatagramPacket packet;

byte[] data;
while (isPlaying)
{
    try
    {
        packet = new DatagramPacket(buffer2, len);
        ds.receive(packet);
        data = new byte[packet.getLength()];
        System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());
        Log.d("UDPserver",  data.length + " bytes received");
    }
    catch()//...........
//...........

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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