如果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
}
}
}