[英]when I use nio, serverSocket.accept() throws IllegalBlockingModeException
When I code like this: 当我像这样编码:
ServerSocketChannel ssc = ServerSocketChannel.open();
InetSocketAddress sa = new InetSocketAddress("localhost",8888);
ssc.socket().bind(sa);
ssc.configureBlocking(false);
ssc.socket().accept();
the ServerSocket.accept()
method throws java.nio.channels.IllegalBlockingModeException
. ServerSocket.accept()
方法抛出java.nio.channels.IllegalBlockingModeException
。 Why can't I call accept()
, even though I set blocking to false
? 为什么我不能调用accept()
,即使我将阻塞设置为false
?
The Javadoc specifically states that ServerSocketChannel.accept()
: Javadoc明确声明ServerSocketChannel.accept()
:
Accepts a connection made to this channel's socket. 接受与此通道的套接字建立的连接。
If this channel is in non-blocking mode then this method will immediately return null if there are no pending connections. 如果此通道处于非阻塞模式,则如果没有挂起的连接,则此方法将立即返回null。 Otherwise it will block indefinitely until a new connection is available or an I/O error occurs. 否则它将无限期阻塞,直到新连接可用或发生I / O错误。
The general idea is: 一般的想法是:
Blocking mode is the default for a reason: Most servers don't want to poll their accepting socket for incoming connections. 阻止模式是默认的原因:大多数服务器不想轮询其接受套接字以获取传入连接。
Because that's what javadoc for serversocket.accept() says? 因为这就是serversocket.accept()所说的javadoc?
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode. IllegalBlockingModeException - 如果此套接字具有关联的通道,并且通道处于非阻塞模式。
The problem is that you are calling ssc.socket().accept()
, not ssc.accept()
. 问题是你正在调用ssc.socket().accept()
,而不是ssc.accept()
。 If you change the last line to ssc.accept()
then it will work as expected, which is to return a SocketChannel if one is waiting or null if not. 如果你将最后一行更改为ssc.accept()
那么它将按预期工作,如果正在等待则返回SocketChannel,否则返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.