Writing an Asynchronous Server Based on CompletionHandler - Java Network

Java examples for Network:Socket Channel

Description

Writing an Asynchronous Server Based on CompletionHandler

Demo Code

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class Main {
  public static void main(String[] args) {
    try (AsynchronousServerSocketChannel asynServerChannel = AsynchronousServerSocketChannel
        .open()) {//from  w ww.  j  av a2s  .c o m
      if (asynServerChannel.isOpen()) {
        asynServerChannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024);
        asynServerChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        asynServerChannel.bind(new InetSocketAddress("127.0.0.1", 5555));
        System.out.println("Waiting for connections ...");
        asynServerChannel.accept(null,
            new CompletionHandler<AsynchronousSocketChannel, Void>() {
              final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
              @Override
              public void completed(AsynchronousSocketChannel result,
                  Void attachment) {
                asynServerChannel.accept(null, this);
                try {
                  System.out.println("Incoming connection from: "
                      + result.getRemoteAddress());
                  while (result.read(buffer).get() != -1) {
                    buffer.flip();
                    result.write(buffer).get();
                    if (buffer.hasRemaining()) {
                      buffer.compact();
                    } else {
                      buffer.clear();
                    }
                  }
                } catch (Exception ex) {
                  System.err.println(ex);
                } finally {
                  try {
                    result.close();
                  } catch (IOException e) {
                    System.err.println(e);
                  }
                }
              }

              @Override
              public void failed(Throwable exc, Void attachment) {
                asynServerChannel.accept(null, this);
                throw new UnsupportedOperationException(
                    "Cannot accept connections!");
              }
            });
        System.in.read();
      } else {
        System.out
            .println("The asynchronous server-socket channel cannot be opened!");
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}

Result


Related Tutorials