DatagramPacket 接收到的附加字节

发布于 2024-12-06 20:56:56 字数 616 浏览 1 评论 0原文

我有一个我第一次看到的问题,我正在使用 java DatagramSocket 在我的应用程序中发送和接收数据。

这就是我发送数据的方式:

byte[] buffer = "my data".getBytes();
senderPacket = new DatagramPacket(buffer, 0, buffer.length, remoteAddress, remotePort);
socket.send(senderPacket);

现在当我发送 byt[] 缓冲区时,它的大小是 275。 但是当我在接收应用程序上收到数据包并从receiverPacket 获取 byte[] 时,如下所示:

buffer = new byte[2048];
receiverPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receiverPacket);

我发现接收到的字节数为 278 个字节,即额外的 3 个字节。

这看起来似乎不是一个大问题,但实际上对我来说,请知道为什么会发生这种情况,以及如何解决它,任何合乎逻辑的解释都会有所帮助。

谢谢

I have a problem that I see for the first time ever, I'm using java DatagramSocket (s) for sending and receiving data in my app.

this is how I send the data:

byte[] buffer = "my data".getBytes();
senderPacket = new DatagramPacket(buffer, 0, buffer.length, remoteAddress, remotePort);
socket.send(senderPacket);

now when I sent the byt[] buffer, it's size was 275.
but when I received the packet on the receiving app and got the byte[] from the receiverPacket, like this:

buffer = new byte[2048];
receiverPacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receiverPacket);

I found that the received bytes count where 278 bytes that's additional 3 bytes.

This might seem like not a big problem, but actually it is for me, please any idea why is this happening, and how to solve it, any logical explanation would be helpful.

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖凝香 2024-12-13 20:56:56

3 个额外字节可以是长度标记。我知道,当我在 C/C++ 中进行套接字时,我通常将前 4 个字节专用于发送消息的长度,然后使用该数据来确定要读取多少内容以读取整个消息。

The 3 extra bytes could be a length marker. I know that when I do sockets in C/C++, I typically dedicate the first 4 bytes to sending the length of my message, and then I use that data to determine how much to read in order to read the entire message.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文