本文介绍了当我使用nio时,serverSocket.accept()抛出IllegalBlockingModeException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样编码时:

ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();

ServerSocket.accept()方法抛出java.nio.channels.IllegalBlockingModeException.即使我将阻止设置为false,为什么我也不能呼叫accept()?

the ServerSocket.accept() method throws java.nio.channels.IllegalBlockingModeException. Why can't I call accept(), even though I set blocking to false?

推荐答案

Javadoc特别声明ServerSocketChannel.accept():

The Javadoc specifically states that ServerSocketChannel.accept():

如果此通道处于非阻塞模式,则此方法将立即 如果没有挂起的连接,则返回null.否则会阻塞 无限期地等待新的连接可用或发生I/O错误.

If this channel is in non-blocking mode then this method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs.

总体思路是:

  • 如果要在等待传入连接时进行阻止,则将服务器套接字置于阻止模式.如果您要编写的服务器在实际建立连接之前无事可做,则您需要的是阻塞模式.
  • 如果您想做其他事情,并定期检查是否有未决的连接,则需要使用非阻塞模式.

默认情况下,阻塞模式是有原因的:大多数服务器不想轮询其接受套接字中的传入连接.

Blocking mode is the default for a reason: Most servers don't want to poll their accepting socket for incoming connections.

这篇关于当我使用nio时,serverSocket.accept()抛出IllegalBlockingModeException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:05