Datagrampacket to string

Trying to convert the resulting DatagramPacket to a string, but I have a little problem. Not sure if this is the best way.

The data that I receive is basically of unknown length, so I have some buffer [1024] installed on my receiving side. The problem is that I sent the string "abc" and will do the following on my side of the recipient ...

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 [] [] [] []] [] [] [] ..... up to the length of the buffer. I assume that all junk / nulls at the end should be ignored, so I have to do something wrong. "I know that the buffer.length problem is a problem, because if I change it to 3 (for this example), my come out just fine.

Thanks.

+4
source share
6 answers
 new String(buffer, 0, packet.getLength()) 
+8
source

The DatagramPacket length field gives the length of the actual packet received. See javadoc for DatagramPacket.receive for more details.

So you just need to use a different String constructor, passing in an array of bytes and the actual byte received.

See for example the answers @jtahlborn or @GiangPhanThanhGiang.


However, this still leaves the problem that character encoding should be used when decoding bytes to a UTF-16 string. For your specific example, this probably doesn't matter. But you are transmitting data, which may include non-ASCII characters, then you need to decode using the correct encoding. If you make a mistake, you may get garbled characters in your String values.

+2
source

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

+2
source

As I understand it, DatagramPacket just has a bunch of garbage at the end. As Stephen S. suggests, you can find the actual length obtained. In this case, use:

 int realSize = packet.getLength() //Method suggested by Stephen C. byte[] realPacket = new byte[realSize]; System.arrayCopy(buffer, 0, realPacket, 0, realSize); 

As for the length search, I do not know.

0
source

Try

 System.out.println("Received: "+new String(buffer).trim()); 

or

 String sentence = new String(packet.getData()).trim(); System.out.println("Received: "+sentence); 
0
source

Use this code instead

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

Source: https://habr.com/ru/post/1386986/


All Articles