如何在Java UDP中获取实际数据包大小`byte[]`数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21868956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:10:14  来源:igfitidea点击:

How to obtain the actual packet size `byte[]` array in Java UDP

javasocketsnetworkingudp

提问by

This is the subsequent question of my previous one: Java UDP send - receive packet one by one

这是我上一个的后续问题: Java UDP发送-接收数据包一一

As I indicated there, basically, I want to receive a packet one by one as it is via UDP.

正如我在那里指出的那样,基本上,我想通过 UDP 一个一个地接收一个数据包。

Here's an example code:

这是一个示例代码:

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");

Here, the actual packet size is say, 300bytes, but the buffer1is allocated as 1024 byte, and to me, it's something wrong with to deal with buffer1.

在这里,实际的数据包大小是 300buffer1字节,但分配为 1024 字节,对我来说,处理buffer1.

How to obtain the actual packet size byte[]array from here?

如何byte[]从这里获取实际的数据包大小数组?

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 )

更根本的是,为什么我们需要像这样在 Java 中预先分配缓冲区大小来接收 UDP 数据包?( node.js 不这样做)

Is there any way not to pre-allocate the buffer size and directly receive the UDP packet as it is?

有没有办法不预先分配缓冲区大小并直接接收UDP数据包?

Thanks for your thought.

谢谢你的想法。

回答by user207421

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 0to index packet.getLength()-1.

你已经回答了你自己的问题。packet.getLength()返回接收到的数据报中的实际字节数。所以,你只需要使用buffer[]from index 0to indexpacket.getLength()-1.

Note that this means that if you're calling receive()in a loop, you have to recreate the DatagramPacketeach 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.

请注意,这意味着如果您receive()在循环中调用,则必须DatagramPacket围绕循环重新创建每次,或者在接收之前将其长度重置为最大值。否则getLength()会一直缩小到迄今为止收到的最小数据报的大小。

回答by user207421

self answer. I did as follows:

自我回答。我做了如下:

int len = 1024;
byte[] buffer2 = new byte[len];
DatagramPacket packet;

byte[] data;
while (isPlaying)
{
    try
    {
        packet = new DatagramPacket(buffer2, len);
        ds.receive(packet);
        data = new byte[packet.getLength()];
        System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());
        Log.d("UDPserver",  data.length + " bytes received");
    }
    catch()//...........
//...........