title: How should I use AsynchronousServerSocketChannel for accepting connections?
body: <p>I would like to write an asynchronous server using Java 7 and NIO 2.</p>
  
  <p>But how should I use <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/channels/AsynchronousServerSocketChannel.html"><code>AsynchronousServerSocketChannel</code></a>?</p>
  
  <p>E.g. if I start with:</p>
  
  <pre><code>final AsynchronousServerSocketChannel server = 
      AsynchronousServerSocketChannel.open().bind(
          new InetSocketAddress(port));
  </code></pre>
  
  <p>Then when I do <code>server.accept()</code>, the program <strong>terminates</strong> because that call is <em>asynchronous</em>. And if I put that code in an infinite loop, an <code>AcceptPendingException</code> is thrown.</p>
  
  <p>Any suggestions on how to write a simple asynchronous server using <code>AsynchronousServerSocketChannel</code>?</p>
  
  <p>Here is my full example (similar to the example in the JavaDoc):</p>
  
  <pre><code>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 AsyncServer {
  
      public static void main(String[] args) {
          int port = 8060;
          try {
              final AsynchronousServerSocketChannel server = 
                      AsynchronousServerSocketChannel.open().bind(
                              new InetSocketAddress(port));
  
              System.out.println("Server listening on " + port);
  
              server.accept("Client connection", 
                      new CompletionHandler&lt;AsynchronousSocketChannel, Object&gt;() {
                  public void completed(AsynchronousSocketChannel ch, Object att) {
                      System.out.println("Accepted a connection");
  
                      // accept the next connection
                      server.accept("Client connection", this);
  
                      // handle this connection
                      //TODO handle(ch);
                  }
  
                  public void failed(Throwable exc, Object att) {
                      System.out.println("Failed to accept connection");
                  }
              });
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>