2

In the code segment below,

DatagramPacket rPacket
rPacket  = new DatagramPacket(new byte[2000], 2000);
.. do some socket.receive ..

what would be the difference between DatagramPacket.getData().length and DatagramPacket.getLength() in java

C graphics
  • 7,308
  • 19
  • 83
  • 134

2 Answers2

2

The difference is that the first returns the size of the array used to construct the object, which never changes; the second returns the smaller of the length supplied to the constructor and the actual length of the smallest datagram most recently received, which changes on every receive.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    @AlexWien It returns the length supplied to the constructor if you haven't received into it. If you have, it returns the length received if smaller, otherwise the length supplied to the constructor. That's what I call a minimum: your definition may vary. Further, if you keep receiving into the same object without resetting it, the length available to receive into keeps shrinking to the smallest packet received so far. That I also call a minimum. – user207421 Nov 26 '12 at 23:12
0

From javadoc of class DataGrammPacket

getLength(): Returns the length of the data to be sent or the length of the data received.

getData(): Returns the data buffer. The data received or the data to be sent starts from the <code>offset</code> in the buffer, and runs for <code>length</code> long.

furthe you have to know the setData():

 Set the data buffer for this packet. This sets the
     * data, length and offset of the packet.
     *
     * @param buf the buffer to set for this packet
     *
     * @param offset the offset into the data
     *
     * @param length the length of the data 
     *       and/or the length of the buffer used to receive data
 setData(byte[] buf, int offset, int length)

The Constructor also calls the setData()

AlexWien
  • 28,470
  • 6
  • 53
  • 83