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