我编写了一个 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
那么我如何获取 12345678 字符串并删除以下“口”内容?
最佳答案
这不是不需要的输出,这是因为您打印了整个缓冲区。
buf.clear();
不会用零清除缓冲区,它只是将位置重置为 0。
关于java - 当我将 ByteBuffer 转换为 String 时,为什么会得到很多不需要的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45093316/