Skip to content

Instantly share code, notes, and snippets.

@yangl
Created April 9, 2014 08:00
Show Gist options
  • Save yangl/10238679 to your computer and use it in GitHub Desktop.
Save yangl/10238679 to your computer and use it in GitHub Desktop.
Java NIO系列教程(六) Selector http://ifeve.com/selectors/
Selector selector = Selector.open();
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
while(true) {
int readyChannels = selector.select();
if(readyChannels == 0) continue;
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
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
}
keyIterator.remove();
// 注意每次迭代末尾的keyIterator.remove()调用。
// Selector不会自己从已选择键集中移除SelectionKey实例。
// 必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment