DatagramPacket to string

前端 未结 6 1166
南旧
南旧 2020-12-11 05:18

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 most

相关标签:
6条回答
  • 2020-12-11 05:57

    As I understand it, the DatagramPacket just has a bunch of junk at the end. As Stephen C. suggests, you might be able to find the actual length received. In that 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 finding the length, I don't know.

    0 讨论(0)
  • 2020-12-11 05:59

    Try

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

    or

    String sentence = new String(packet.getData()).trim();
    System.out.println("Received: "+sentence);
    
    0 讨论(0)
  • 2020-12-11 06:01

    The DatagramPacket's length field gives the length of the actual packet received. Refer to the javadoc for DatagramPacket.receive for more details.

    So you simply need to use a different String constructor, passing the byte array and the actual received byte count.

    See @jtahlborn or @GiangPhanThanhGiang's answers for example.


    However, that still leaves the problem of which character encoding should be used when decoding the bytes into a UTF-16 string. For your particular example it probably doesn't matter. But it you are passing data that could include non-ASCII characters, then you need to decode using the correct charset. If you get that wrong, you are liable to get garbled characters in your String values.

    0 讨论(0)
  • 2020-12-11 06:02

    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);
    
    0 讨论(0)
  • 2020-12-11 06:03
    new String(buffer, 0, packet.getLength())
    
    0 讨论(0)
  • 2020-12-11 06:10

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

    0 讨论(0)
提交回复
热议问题