Search code examples
javanio

Why I get a lot of unwanted output when I convert ByteBuffer to String?


I write a UDP server to receive messages from clients using NIO:

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.clear();
while (channel.receive(buf) != null) {
      System.out.println("---has received data:" + new String(buf.array(), ASCII));
      buf.clear();
}

then I use nc command to send some data to the UDP server

nc -u 127.0.0.1 9999 < ./test.txt

there is only one line in test.txt

#cat ./test.txt
12345678

and the output of the server is like this enter image description here

so how could I get the 12345678 string and remove the following '口' things?


Solution

  • DatagramChannel channel = DatagramChannel.open();
    channel.socket().bind(new InetSocketAddress(9999));
    
    ByteBuffer chunkData = ByteBuffer.allocate(1024);
    chunkData.clear();
    
    channel.receive(chunkData);
    
    // remove unwanted data
    byte[] validData = new byte[chunkData.position()];
    System.arraycopy(chunkData.array(), 0, validData, 0, validData.length);
    
    System.out.println("---has received data:" + new String(validData));