2012-11-26 56 views
2

在下面的代码段DatagramPacket.getData()。长度和DatagramPacket.getLength()差异性之探源,什么是Java中

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

这将是DatagramPacket.getData()。长度和DatagramPacket类的区别java中的.getLength()

+0

看源代码或javadocs ... – mre

回答

2

区别在于第一个返回用于构造对象的数组的大小,它永远不会改变;第二个返回提供给构造函数的长度中较小的一个,以及最近接收到的最小数据报的实际长度,这在每个接收中都会发生变化。

+1

@AlexWien它返回提供给构造函数的长度,如果你还没有收到。如果有,则返回收到的长度(如果较小),否则返回给构造函数的长度。这就是我所说的最低限度:你的定义可能会有所不同。此外,如果您不重置接收到相同的对象,则可用于接收的长度会不断缩小到目前为止收到的最小数据包。我也称最低限度。 – EJP

+0

好的,这说明 – AlexWien

0

从类DataGrammPacket的javadoc的

的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你必须知道 使用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) 

的构造函数也调用setData()

+0

最后一句与第一句矛盾,应该删除。 – EJP

+0

这是javadoc原创,我没有看到矛盾。请删除downvote,并再次考虑 – AlexWien

+0

现在,您已完全重写您的答案,现在*不存在矛盾。 – EJP