NIO

public void run(){ try { while (keepRunning) { doSelection (selector); } serverSocketChannel.close(); selector.close(); } catch (Exception e) { logger.fatal ("Unexpected exception: ", e); }}protected void doSelection (Selector selector) throws IOException{ selector.select(); if ( ! keepRunning) return; for (Iterator it = selector.selectedKeys().iterator(); it.hasNext();) { SelectionKey key = (SelectionKey) it.next(); it.remove(); if (key.isAcceptable()) { acceptNewConnection (key); continue; } Connection connection = (Connection) key.attachment(); if (key.isWritable()) { connection.drainOutput(); continue; } if (key.isReadable()) { connection.readInput(); drainQueuedMessages (connection); continue; } }}protected void acceptNewConnection (SelectionKey serverKey) throws IOException{ ServerSocketChannel serverSocketChannel = (ServerSocketChannel) serverKey.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); User user = new GenericUser (null); socketChannel.configureBlocking (false); SelectionKey key = socketChannel.register ( serverKey.selector(), SelectionKey.OP_READ); Connection connection = new NIOConnection (this, user, getProtocol(), key); key.attach (connection); connection.startup();}