简体   繁体   English

DatagramPacket接收的其他字节

[英]Additional bytes received by a DatagramPacket

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. 我有一个第一次遇到的问题,我正在使用java DatagramSocket在我的应用程序中发送和接收数据。

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: 现在,当我发送byt []缓冲区时,它的大小为275。但是当我在接收应用程序上接收到数据包并从receiverPacket中获得了byte []时,如下所示:

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. 我发现接收到的字节数为278个字节,即另外3个字节。

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 谢谢

The 3 extra bytes could be a length marker. 3个额外的字节可能是长度标记。 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. 我知道当我使用C / C ++进行套接字时,通常将前4个字节专用于发送消息的长度,然后使用该数据确定读取多少以便读取整个消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM