Writing to a SocketChannel Writing data to a SocketChannel is done using the SocketChannel.write() method, which takes a Buffer as parameter. Here is an example:
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
channel.write(buf);
}
Notice how the SocketChannel.write() method is called inside a while-loop. There is no guarantee of how many bytes the write() method writes to the SocketChannel. Therefore we repeat the write() call until the Buffer has no further bytes to write.
出处: http://tutorials.jenkov.com/java-nio/socketchannel.html
上述教程说 socketchannel 应该放在 while 循环中进行写入数据,但是看网上的很多例子,并没有放入循环中,自己跑起来也能对,如 https://zhuanlan.zhihu.com/p/27365009 , 想知道哪种使用方法是正确的,谢谢解答
1
SoloCompany 2019-02-23 18:58:48 +08:00
你需要阻塞就老老实实用 bio, 用阻塞思想写出这样的代码就是死循环消耗大量无谓的 cpu
|
2
zjp 2019-02-25 14:33:22 +08:00
“ Notice how the SocketChannel.write() method is called inside a while-loop. There is no guarantee of how many bytes the write() method writes to the SocketChannel. Therefore we repeat the write() call until the Buffer has no further bytes to write.” 这段话已经说明白了。
因为一般示例代码里的数据量不大,一次性写入通常都能写完,看起来没什么问题...可以加大数据量试试 |