public class Server { private static boolean shutdownListener; public static void main(String[] args) { if (args.length != 1) { System.err.println("Usage: java Server "); System.exit(1); } try { int port = Integer.parseInt(args[0]); try { ServerSocketChannel ssChannel = ServerSocketChannel.open(); ssChannel.configureBlocking(false); ssChannel.socket().bind(new InetSocketAddress(port)); System.out.println("Listening for connections on port " + port); Selector selector = Selector.open(); ssChannel.register(selector, SelectionKey.OP_ACCEPT); while (!shutdownListener) { selector.select(); Iterator it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next(); it.remove(); if (selKey.isAcceptable()) { ServerSocketChannel zzChannel = (ServerSocketChannel) selKey.channel(); SocketChannel sChannel = zzChannel.accept(); if (sChannel != null) { sChannel.register(selector, sChannel.validOps()); } else { // Is this even possible? } } try { if (selKey.isValid() && selKey.isConnectable()) { SocketChannel sChannel = (SocketChannel) selKey.channel(); boolean success = sChannel.finishConnect(); if (!success) { // Do some error handling or whatever. selKey.cancel(); } } if (selKey.isValid() && selKey.isReadable()) { SocketChannel zChannel = (SocketChannel) selKey.channel(); // Reading } if (selKey.isValid() && selKey.isWritable()) { SocketChannel zChannel = (SocketChannel) selKey.channel(); // Writing } } catch (IOException e) { selKey.cancel(); } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } catch (NumberFormatException e) { System.err.println("Usage: java Server "); System.exit(1); } } }