DatagramPacket to string

user1105216 picture user1105216 · Dec 19, 2011 · Viewed 20.2k times · Source

Trying to convert a received DatagramPacket to string, but I have a small problem. Not sure what's the best way to go about it.

The data I'll be receiving is mostly of unknown length, hence I have some buffer[1024] set on my receiving side. The problem is, suppose I sent string "abc" and the do the following on my receiver side...

buffer = new byte[1024]; 
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
buffer = packet.getData();
System.out.println("Received: "+new String(buffer));

I get the following output: abc[][][][]][][][]..... all the way to the buffer length. I'm guessing all the junk/null at the end should've been ignored, so I must be doing something wrong." I know the buffer.length is the problem because if I change it to 3 (for this example), my out comes out just fine.

Thanks.

Answer

jtahlborn picture jtahlborn · Dec 19, 2011
new String(buffer, 0, packet.getLength())