Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DatagramPacket - will getData always return the same buffer which is passed?

byte [] r = new byte[4096];
DatagramPacket dpr = new DatagramPacket(r, r.length);
sock.receive(dpr);

After the receive, will dpr.getData() & r always be the same?

ex: Can I directly use the byte array r or do I need to call getData() to retrieve the buffer again?

Testing it, showed it to be the same, but is this always guaranteed?

like image 753
user93353 Avatar asked Jun 01 '16 05:06

user93353


1 Answers

byte [] r = new byte[4096];
DatagramPacket dpr = new DatagramPacket(r, r.length);
sock.receive(r);

That should be sock.receive(dpr);

After the receive, will dpr.getData() & r always be the same?

Yes. r was supplied to the constructor as 'the buffer for holding the incoming datagram', and getData() 'returns the buffer used to receive or send data'.

i.e. can I directly use the byte array r or do I need to call getData() to retrieve the buffer again?

You can use the byte array, but why? Use getData() like everybody else, not forgetting to also use getOffset() and getLength(), rather than assuming the datagram filled the byte array: for example, System.out.println(new String(datagram.getData(), datagram.getOffset(), datagram.getLength()));

like image 170
user207421 Avatar answered Sep 18 '22 09:09

user207421