Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Reading n bytes from DatagramSocket without loosing the rest of the packet

807607Oct 11 2006 — edited Oct 11 2006
Sending Side:
-----------------
I want to send a packet in which I concatinate the size of y data as a header and the data as a trailer. My packet before I send is:
| n [4 bytes] | + | data [n bytes] |
for instance If I want to send "java" then my packet look like ['4','j','a','v','a']
I send it via
socket.send (packet)
Receiver side
------------------
On the receiver side I would like to read the first 4 bytes, get the size of the data and then read the rest of the packet:
packet = new DatagramPacket(new byte[4], 4);
socket.receive (packet);

int size = byteArraytoInt (packet .getData());

packet = new DatagramPacket(new byte[size ], size);
socket.receive (packet);
My problem
----------------
The function "socket.receive (packet)" receives the first packet and thus will discard the rest of my first packet. So the second time I perform a receive I will be actually reading the next packet and not the data trailer of the first packet.

Any solutions!!!!! Please. I am stuck for days on this :(
Will using DatagramChanel solve the problem!?!?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 8 2006
Added on Oct 11 2006
3 comments
309 views