AIO(Asynchronous IO)即异步IO,特别需要说明的是,Java AIO需要JDK 1.7的支持
客户端
package com.test.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import com.test.handler.client.ConnectCompleteHandler;
public class Client {
private Logger logger = Logger.getLogger(Client.class);
private String host = "127.0.0.1";
private int port = 9999;
private int poolSize = 10;
private static CountDownLatch serverStatus = new CountDownLatch(1);
public Client() throws Exception {
try {
//池中的每个线程都在等待IO事件,当IO操作完成后,调用池中的线程处理CompleteHandler
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
AsynchronousChannelGroup asyncChannelGroup
= AsynchronousChannelGroup.withThreadPool(threadPool);
AsynchronousSocketChannel asyncSocketChannel =
AsynchronousSocketChannel.open(asyncChannelGroup);
asyncSocketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
asyncSocketChannel.connect(new InetSocketAddress(host, port),
null, new ConnectCompleteHandler(asyncSocketChannel));
} catch (IOException e) {
logger.error("Cilent socket establish failed!");
throw e;
}
}
public static void main(String[] args) throws Exception {
Client client = new Client();
serverStatus.await();
}
}
客户端处理器
package com.test.handler.client;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import org.apache.log4j.Logger;
//CompletionHandler<V,A>
//V-IO操作的结果,AsynchronousSocketChannel.open创建的异步连接,
// asyncSocketChannel.connect实际没有IO操作,因此IO操作的结果为Void
//A-IO操作附件,
public class ConnectCompleteHandler
implements CompletionHandler<Void, Object> {
private Logger logger = Logger.getLogger(ConnectCompleteHandler.class);
AsynchronousSocketChannel asyncSocketChannel;
public ConnectCompleteHandler(
AsynchronousSocketChannel asyncSocketChannel){
this.asyncSocketChannel = asyncSocketChannel;
}
@Override
public void completed(Void result, Object attachment) {
//使用asyncChannelGroup中保存的线程池中的线程进行处理
logger.info("Deal thread of [ConnectCompleteHandler] : "
+ Thread.currentThread().getName());
String request = "Hi, this is client!";
logger.info("The request sent by client is : " + request);
try {
byte[] reqBytes = request.getBytes("utf-8");
ByteBuffer writeByteBuffer = ByteBuffer.allocate(reqBytes.length);
writeByteBu