ServerSocketChannel ssc = ServerSocketChannel.open();
Selector selector = Selector.open();
ssc.socket().bind (new InetSocketAddress (PORT_NUMBER));
ssc.configureBlocking (false);
ssc.register (selector, SelectionKey.OP_ACCEPT);
while (true) {
int n = selector.select (1000);
System.out.println ("selector returns: " + n);
Iterator it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
// Is a new connection coming in?
if (key.isAcceptable()) {
ServerSocketChannel server =
(ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
// set the new channel non-blocking
channel.configureBlocking (false);
// register it with the selector
channel.register (selector,
SelectionKey.OP_READ);
it.remove();
}
// is there data to read on this channel?
if (key.isReadable()) {
System.out.println ("Channel is readable");
// don't actually do anything
}
// it.remove();
}
}