DatagramPacket 接收到的附加字节
我有一个我第一次看到的问题,我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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.