Java nio socketchannel write 方法使用问题

2019-02-22 09:20:17 +08:00
 MaybeSilent

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 , 想知道哪种使用方法是正确的,谢谢解答

1562 次点击
所在节点    Java
2 条回复
SoloCompany
2019-02-23 18:58:48 +08:00
你需要阻塞就老老实实用 bio, 用阻塞思想写出这样的代码就是死循环消耗大量无谓的 cpu
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.” 这段话已经说明白了。
因为一般示例代码里的数据量不大,一次性写入通常都能写完,看起来没什么问题...可以加大数据量试试

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/537491

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX