V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MaybeSilent
V2EX  ›  Java

Java nio socketchannel write 方法使用问题

  •  
  •   MaybeSilent · 2019-02-22 09:20:17 +08:00 · 1554 次点击
    这是一个创建于 2121 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    2 条回复    2019-02-25 14:33:22 +08:00
    SoloCompany
        1
    SoloCompany  
       2019-02-23 18:58:48 +08:00
    你需要阻塞就老老实实用 bio, 用阻塞思想写出这样的代码就是死循环消耗大量无谓的 cpu
    zjp
        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.” 这段话已经说明白了。
    因为一般示例代码里的数据量不大,一次性写入通常都能写完,看起来没什么问题...可以加大数据量试试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4838 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 08:57 · PVG 16:57 · LAX 00:57 · JFK 03:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.