import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; public class TCPServerAsync { private static final int BUFSIZE = 256; // Buffer size (bytes) public static void main(String[] args) throws IOException, InterruptedException { if (args.length != 1) { // Test for correct # of args throw new IllegalArgumentException("Parameter(s): "); } int port = Integer.parseInt(args[0]); final TCPProtocol protocol = new EchoAsyncProtocol(BUFSIZE); final AsynchronousServerSocketChannel listnChannel = AsynchronousServerSocketChannel.open(); listnChannel.bind(new InetSocketAddress(port)); listnChannel.accept(null, new CompletionHandler() { public void cancelled(Void attachment) { die(); } public void completed(final AsynchronousSocketChannel clntChan, Void attachment) { listnChannel.accept(null, this); try { protocol.handleAccept(clntChan); } catch (IOException e) { } } public void failed(Throwable exception, Void attachment) { die(exception); } } ); Thread.sleep(500000); } private static void die(Throwable e) { e.printStackTrace(); die(); } private static void die() { System.exit(1); } }