【问题标题】:What's the diffrence between DatagramPacket.getData().length and DatagramPacket.getLength() in javajava中DatagramPacket.getData().length和DatagramPacket.getLength()有什么区别
【发布时间】:2012-11-14 11:53:51
【问题描述】:

在下面的代码段中,

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

Java中DatagramPacket.getData().length和DatagramPacket.getLength()有什么区别

【问题讨论】:

  • 查看源代码或javadocs...

标签: java sockets udp datagram


【解决方案1】:

不同的是,第一个返回的是用于构造对象的数组的大小,永远不会改变;第二个返回提供给构造函数的长度和最近收到的最小数据报的实际长度中较小的一个,每次接收都会改变。

【讨论】:

  • @AlexWien 如果您没有收到它,它会返回提供给构造函数的长度。如果有,则返回收到的长度(如果较小),否则返回提供给构造函数的长度。这就是我所说的最低限度:您的定义可能会有所不同。此外,如果您继续接收到同一个对象而不重置它,则可接收到的长度会不断缩小到迄今为止接收到的最小数据包。我也称之为最低限度。
【解决方案2】:

来自 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.

你必须知道 设置数据():

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

【讨论】:

  • 最后一句和第一句矛盾,应该删掉。
  • 这是原始的 javadoc 文档,我看不出矛盾。请删除反对票,然后再考虑
  • 现在你已经完全重写了你的答案,没有矛盾。
  • 我已经添加了有关长度的信息,但没有更改原文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 2023-03-03
  • 2021-04-13
  • 2021-05-30
  • 1970-01-01
  • 2011-11-23
相关资源
最近更新 更多