Reactor Design Pattern(Using java nio)By: Allan S. Lim
SelectorSelector selector = Selector.open();
SelectorsscServerSocketChannelssc = ServerSocketChannel.open();ssc.configureBlocking( false );ServerSocketss = ssc.socket();InetSocketAddress address = new InetSocketAddress(port);ss.bind( address );
registerSelectorsscacceptSelectionKey key = ssc.register( selector, SelectionKey.OP_ACCEPT );
registeraccept handlerSelectorsscacceptint num = selector.select();Set selectedKeys = selector.selectedKeys();Iterator it = selectedKeys.iterator();while (it.hasNext()) {SelectionKey key = (SelectionKey)it.next();   if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {       // Accept the new connection and send to a handler.     }}
registeraccept handlerSelectorsscacceptreadscreadhandlerServerSocketChannelssc = (ServerSocketChannel)key.channel();SocketChannel sc = ssc.accept();sc.configureBlocking( false );SelectionKeynewKey = sc.register( selector, SelectionKey.OP_READ );
registeraccept handlerSelectorsscacceptreadscreadhandler if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {       // Accept the new connection and send to a handler. } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {       // Read the data and send the handler.SocketChannelsc = (SocketChannel)key.channel();}
registeraccept handlerSelectorsscacceptreadscreadhandlerwritescwritehandlerIt’s the same process with the write handler.
registeraccept handlerSelectorsscacceptreadscreadhandlerwritescwritehandlerYou can have an array of handlers.
CLIENTSregisteraccept handlerSelectorsscacceptreadscreadhandlerwritescwritehandlerFor each client event, the selector will notify the handler, and return to listening to event again.

Reactor Design Pattern