"
在使用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
"
"
猜测是你设置的不准确,按照你的代码,我做了测试:
<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
######没有规定必须一次就把全部数据写完吧,
"版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。