import java.nio.*; import java.nio.channels.*; import java.net.*; import java.util.*; import java.io.IOException; public class EchoServer { public static int DEFAULT_PORT = 7; public static void main(String[] args) { int port; try { port = Integer.parseInt(args[0]); } catch (Exception ex) { port = DEFAULT_PORT; } System.out.println("Listening for connections on port " + port); ServerSocketChannel serverChannel; Selector selector; try { // create server channel serverChannel = ServerSocketChannel.open(); // extract server socket of the server channel and bind the port ServerSocket ss = serverChannel.socket(); InetSocketAddress address = new InetSocketAddress(port); ss.bind(address); // configure it to be non blocking serverChannel.configureBlocking(false); // register the server channel to a selector selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); } catch (IOException ex) { ex.printStackTrace(); return; } while (true) { try { // check to see if any events selector.select(); } catch (IOException ex) { ex.printStackTrace(); break; } // readKeys is a set of ready events Set readyKeys = selector.selectedKeys(); // create an iterator for the set Iterator iterator = readyKeys.iterator(); // iterate over all events while (iterator.hasNext()) { SelectionKey key = (SelectionKey) iterator.next(); iterator.remove(); try { if (key.isAcceptable()) { // a new connection is ready to be accepted ServerSocketChannel server = (ServerSocketChannel ) key.channel(); // extract the ready connection SocketChannel client = server.accept(); System.out.println("Accepted connection from " + client); // configure the connection to be non-blocking client.configureBlocking(false); // register the new connection with read and write events/operations SelectionKey clientKey = client.register( selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ); // attach a buffer to the new connection ByteBuffer buffer = ByteBuffer.allocate(100); clientKey.attach(buffer); } // end of isAcceptable if (key.isReadable()) { // a connection is ready to be read SocketChannel client = (SocketChannel) key.channel(); ByteBuffer output = (ByteBuffer) key.attachment(); client.read(output); } // end of isReadable if (key.isWritable()) { SocketChannel client = (SocketChannel) key.channel(); ByteBuffer output = (ByteBuffer) key.attachment(); output.flip(); client.write(output); output.compact(); } // end of if isWritable } catch (IOException ex) { key.cancel(); try { key.channel().close(); } catch (IOException cex) {} } // end of catch } // end of while (iterator.hasNext()) { } // end of while (true) } // end of main } // end of class