如何在 Java UDP 中获取实际数据包大小 `byte[]` 数组
这是我上一个问题的后续问题:Java UDP 发送 - 一个一个接收数据包
This is the subsequent question of my previous one: Java UDP send - receive packet one by one
正如我在那里指出的,基本上,我想通过 UDP 一个接一个地接收数据包.
As I indicated there, basically, I want to receive a packet one by one as it is via UDP.
这是一个示例代码:
ds = new DatagramSocket(localPort);
byte[] buffer1 = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer1, buffer1.length);
ds.receive(packet);
Log.d("UDP-receiver", packet.getLength()
+ " bytes of the actual packet received");
这里,实际的数据包大小是 300 字节,但 buffer1
分配为 1024 字节,对我来说,处理 buffer1
是有问题的.
Here, the actual packet size is say, 300bytes, but the buffer1
is allocated as 1024 byte, and to me, it's something wrong with to deal with buffer1
.
如何从这里获取实际数据包大小byte[]
数组?
How to obtain the actual packet size byte[]
array from here?
而且,更根本的是,为什么我们需要像这样在 Java 中预先分配缓冲区大小来接收 UDP 数据包?(node.js 不这样做)
and, more fundamentally, why do we need to preallocate the buffer size to receive UDP packet in Java like this? ( node.js doesn't do this )
有没有办法不预先分配缓冲区大小,直接接收UDP包?
Is there any way not to pre-allocate the buffer size and directly receive the UDP packet as it is?
感谢您的想法.
推荐答案
您已经回答了自己的问题.packet.getLength()
返回接收到的数据报中的实际字节数.因此,您只需使用索引 0
中的 buffer[]
来索引 packet.getLength()-1.
You've answered your own question. packet.getLength()
returns the actual number of bytes in the received datagram. So, you just have to use buffer[]
from index 0
to index packet.getLength()-1.
请注意,这意味着如果您在循环中调用 receive()
,则每次循环时都必须重新创建 DatagramPacket
,或重置其长度最大接收前.否则 getLength()
会一直缩小到目前收到的最小数据报的大小.
Note that this means that if you're calling receive()
in a loop, you have to recreate the DatagramPacket
each time around the loop, or reset its length to the maximum before the receive. Otherwise getLength()
keeps shrinking to the size of the smallest datagram received so far.
相关文章