How to get rid of the empty remaining of the buffer?

Miky picture Miky · Nov 22, 2011 · Viewed 9.1k times · Source

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: string buffer null characters

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);

Answer

Afrig Aminuddin picture Afrig Aminuddin · Oct 11, 2013
socket.receive(packet);
byte[] data = new byte[packet.getLength()];
System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());