What's the diffrence between DatagramPacket.getData().length and DatagramPacket.getLength() in java

空扰寡人 提交于 2019-12-11 01:55:21

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/13574436/whats-the-diffrence-between-datagrampacket-getdata-length-and-datagrampacket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!