如果Socket
有一个关联的SocketChannel
,则不能直接读取它的InputStream
。你会得到IllegalBlockingModeException
。见here。
您可以通过registering阻止非阻塞SocketChannel到Selector并使用select()或select(long timeout)。这些方法通常会阻塞,直到注册的通道准备就绪(或超时过期)。
对于不使用选择器的线程,通道仍然是非阻塞的。
从
here
变形例:
Selector selector = Selector.open();
channel.configureBlocking(false);
// register for OP_READ: you are interested in reading from the channel
channel.register(selector, SelectionKey.OP_READ);
while (true) {
int readyChannels = selector.select(); // This one blocks...
// Safety net if the selector awoke by other means
if (readyChannels == 0) continue;
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (!key.isValid()) {
continue;
} else if (key.isAcceptable()) {
// a connection was accepted by a ServerSocketChannel.
} else if (key.isConnectable()) {
// a connection was established with a remote server.
} else if (key.isReadable()) {
// a channel is ready for reading
} else if (key.isWritable()) {
// a channel is ready for writing
}
}
}