当我将ByteBuffer转换为String时,为什么会出现大量不需要的输出?

时间:2017-07-14 01:43:14

标签: java nio

我编写UDP服务器以使用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();
}

然后我使用nc命令将一些数据发送到UDP服务器

nc -u 127.0.0.1 9999 < ./test.txt

test.txt中只有一行

#cat ./test.txt
12345678

并且服务器的输出是这样的 enter image description here

那我怎么能得到12345678字符串并删除下面的'口'呢?

3 个答案:

答案 0 :(得分:2)

这不是不需要的输出,这是因为您打印了整个缓冲区。

buf.clear();不会用零清除缓冲区,只是将位置重置为0。

答案 1 :(得分:1)

Intent intent = new Intent(this, MyReceiver.class); // You wanted receiver

// PendingIntent was created in such a way 
// you wanted this to be received by an activity. 
// you will not receive any call if you set it up like this.
PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_*); 

答案 2 :(得分:1)

System.out.println("---has received data:" + new String(buf.array(), ASCII));

您忽略了数据报长度。这应该是:

System.out.println("---has received data:" + new String(buf.array(), 0, buf.position()-1, ASCII));