I have a server-client application that is using a datagram socket to exchange messages. I have initially set the buffer size to be 1024 bytes because I dont know the length of the messages. When I send something that is shorter than 1024 bytes I get the rest of my string displayed as some weird characters (null characters or I am not sure how they are called).
Here is a screen:
Client code:
byte[] buf = ("This is another packet.\n").getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, inetAddress, serverport);
socket.send(packet)
Server code:
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
Ok so I came up with a solution that worked for me:
EDIT: There exists a better solution using
ByteArrayOutputStream
which can be found here: How to reinitialize the buffer of a packet?You have to check
packet.getOffset()
to find where in the buffer the received data starts andpacket.getLength()
to get the length of the data (in number of bytes).You should also consider that if the received packet is too large to fit in the provided buffer (in your case >1024 bytes), the extra data is simply discarded. Unless you have to be very careful on memory usage, you should use a larger buffer to make sure that the entire packet will fit. In case of UDP, the maximum packet size is 64kB.
DatagramPacket.getLength()
returns the actual length of the received packet. Unless you created the packet with a non-zero offet, that means the data is at{0..getLength()-1}
.Note that this means the original length you created the
DatagramPacket
with is lost, which in turn implies that you must either use a newDatagramPacket
per receive, or at least re-initalize its data buffer viasetData()
. Otherwise theDatagramPacket
will keep shrinking to the size of the smallest packet received.