MaybeSilent
V2EX  ›  Java

Java nio socketchannel write 方法使用问题

  •  
  •   MaybeSilent · Feb 22, 2019 · 2001 views
    This topic created in 2648 days ago, the information mentioned may be changed or developed.

    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 replies    2019-02-25 14:33:22 +08:00
    SoloCompany
        1
    SoloCompany  
       Feb 23, 2019
    你需要阻塞就老老实实用 bio, 用阻塞思想写出这样的代码就是死循环消耗大量无谓的 cpu
    zjp
        2
    zjp  
       Feb 25, 2019
    “ 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.” 这段话已经说明白了。
    因为一般示例代码里的数据量不大,一次性写入通常都能写完,看起来没什么问题...可以加大数据量试试
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2872 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 04:14 · PVG 12:14 · LAX 21:14 · JFK 00:14
    ♥ Do have faith in what you're doing.