开发者社区> 问答> 正文

Java NIO写入异常问题报错

"

在使用NIO进行写入数据时,我把缓冲区增大1000k,为什么这时会出现没有写完的情况??

public class Server {

public static void main(String[] args) throws Exception { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress("localhost", 7077));

Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
selector.select();
Set<SelectionKey> selectedKeysSet = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeysSet.iterator();
while (iterator.hasNext()) {
  SelectionKey key = iterator.next();
  SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
  socketChannel.configureBlocking(false);
  ByteBuffer byteBuffer = ByteBuffer.allocate(1000 * 1024);
  System.out.println("byteBuffer.limit()=" + byteBuffer.limit());
  socketChannel.write(byteBuffer);
  System.out.println("byteBuffer.position()=" + byteBuffer.position());
  socketChannel.close();
}
serverSocketChannel.close();

} }

public class Client {

public static void main(String[] args) throws Exception { SocketChannel channel1 = SocketChannel.open(); channel1.connect(new InetSocketAddress("localhost", 7077)); TimeUnit.MINUTES.sleep(1); channel1.close(); } }

byteBuffer.limit()=1024000

byteBuffer.position()=261676

"

展开
收起
因为相信,所以看见。 2020-05-27 10:00:28 913 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    "

    猜测是你设置的不准确,按照你的代码,我做了测试:

    <code class=""java"">while (iterator.hasNext()) { SelectionKey key = iterator.next(); SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept(); //设置缓冲区大小 socketChannel.setOption(StandardSocketOptions.SO_SNDBUF,1000 * 1024);

    System.out.println(socketChannel.getOption(StandardSocketOptions.SO_SNDBUF));
    socketChannel.configureBlocking(false);
    ByteBuffer byteBuffer = ByteBuffer.allocate(1000 * 1024);
    System.out.println("byteBuffer.limit()=" + byteBuffer.limit());
    System.out.println(socketChannel.write(byteBuffer));
    System.out.println("byteBuffer.position()=" + byteBuffer.position());
    socketChannel.close();
    

    }

    //输出 1024000 byteBuffer.limit()=1024000 1024000 byteBuffer.position()=1024000

    ######

    没有规定必须一次就把全部数据写完吧,

    "

    2020-05-27 17:52:25
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载