简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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