Reputation:
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.
Upvotes: 14
Views: 19815
Reputation:
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()//...........
//...........
Upvotes: 4
Reputation: 310980
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.
Upvotes: 6