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 usebuffer[]
from index0
to indexpacket.getLength()-1.
Note that this means that if you're calling
receive()
in a loop, you have to recreate theDatagramPacket
each time around the loop, or reset its length to the maximum before the receive. OtherwisegetLength()
keeps shrinking to the size of the smallest datagram received so far.self answer. I did as follows: