Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DatagramPacket to string

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.

like image 435
user1105216 Avatar asked Dec 19 '11 04:12

user1105216


2 Answers

new String(buffer, 0, packet.getLength())
like image 134
jtahlborn Avatar answered Sep 18 '22 03:09

jtahlborn


Using this code instead: String msg = new String(packet.getData(), packet.getOffset(), packet.getLength());

like image 23
Giang Phan Avatar answered Sep 19 '22 03:09

Giang Phan