packageorg.windwant.io.aio;importjava.io.IOException;importjava.net.InetSocketAddress;importjava.nio.ByteBuffer;importjava.nio.channels.AsynchronousChannelGroup;importjava.nio.channels.AsynchronousServerSocketChannel;importjava.nio.channels.AsynchronousSocketChannel;importjava.nio.channels.CompletionHandler;importjava.nio.charset.Charset;importjava.util.concurrent.ExecutionException;importjava.util.concurrent.Executors;importjava.util.concurrent.ThreadLocalRandom;/*** AsynchronousServerSocketChannel*/
public class AIOServer implementsRunnable{private int port = 8889;private int threadSize = 10;protectedAsynchronousChannelGroup asynchronousChannelGroup;protectedAsynchronousServerSocketChannel serverChannel;public AIOServer(int port, intthreadSize) {this.port =port;this.threadSize =threadSize;
init();
}private voidinit(){try{
asynchronousChannelGroup= AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 10);
serverChannel=AsynchronousServerSocketChannel.open(asynchronousChannelGroup);
serverChannel.bind(newInetSocketAddress(port));
System.out.println("listening on port: " +port);
}catch(IOException e) {
e.printStackTrace();
}
}public voidrun() {try{if(serverChannel == null) return;
serverChannel.accept(this, new CompletionHandler() {final ByteBuffer echoBuffer = ByteBuffer.allocateDirect(1024);public voidcompleted(AsynchronousSocketChannel result, AIOServer attachment) {
System.out.println("==============================================================");
System.out.println("server process begin ...");try{
System.out.println("client host: " +result.getRemoteAddress());
echoBuffer.clear();
result.read(echoBuffer).get();
echoBuffer.flip();
System.out.println("received : " +Charset.defaultCharset().decode(echoBuffer));int random = ThreadLocalRandom.current().nextInt(5);
printProcess(random);
System.out.println("server deal request execute: " + random + "s");
String msg= "server test msg-" +Math.random();
System.out.println("server send data: " +msg);
result.write(ByteBuffer.wrap(msg.getBytes()));
System.out.println("server process end ...");
}catch(IOException e) {
e.printStackTrace();
}catch(InterruptedException e) {
e.printStackTrace();
}catch(ExecutionException e) {
e.printStackTrace();
}finally{
attachment.serverChannel.accept(attachment,this);//监听新的请求,递归调用。
}
}public voidfailed(Throwable exc, AIOServer attachment) {
System.out.println("received failed");
exc.printStackTrace();
attachment.serverChannel.accept(attachment,this);
}
});
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}private void printProcess(int s) throwsInterruptedException {
String dot= "";for (int i = 0; i < s; i++) {
Thread.sleep(1000);
dot+= ".";
System.out.println(dot);
}
}public static void main(String[] args) throwsIOException {new Thread(new AIOServer(8989, 19)).start();
}
}