JDK1.7 提供了全新的异步NIO模式。称为:NIO2.0或AIO。该模式引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。异步通道提供两种方式获取获取操作结果。分别是:
- 通过java.util.concurrent.Future类来表示异步操作的结果;
- CompletionHandler接口的实现类作为操作完成的回调。
NIO2.0的异步套接字通道是真正的异步非阻塞I/O,它对应UNIX网络编程中的事件驱动I/O(AIO),它不需要通过多路复用器(Selector)对注册的通道进行轮询操作即可实现异步读写,从而简化了NIO的编程模型。
回调模式
AIO的回调模式的服务端代码:
public class SocketServiceCb {
AsynchronousServerSocketChannel asynchronousServerSocketChannel;
CountDownLatch latch;
public void start() {
try {
asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
asynchronousServerSocketChannel.bind(new InetSocketAddress("127.0.0.1", 17777));
} catch (IOException e) {
e.printStackTrace();
}
latch = new CountDownLatch(1);
doAccept();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doAccept() {
asynchronousServerSocketChannel.accept(this, new AccessCompleteHandler());
}
class AccessCompleteHandler implements CompletionHandler<AsynchronousSocketChannel, SocketServiceCb> {
@Override
public void completed(AsynchronousSocketChannel result, SocketServiceCb attachment) {
// 当我们调用AsynchronousServerSocketChannel的accept方法后,如果有新的客户端连接接入,
// 系统将回调我们传入的CompletionHandler实例的completed方法,表示新的客户端已经接入成功,
// 因为一个AsynchronousServerSocket Channel可以接收成千上万个客户端,
// 所以我们需要继续调用它的accept方法,接收其他的客户端连接,
// 最终形成一个循环。每当接收一个客户读连接成功之后,再异步接收新的客户端连接。
attachment.asynchronousServerSocketChannel.accept(attachment, this);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
byteBuffer.flip();
//参数1 ByteBuffer dst:接收缓冲区,用于从异步Channel中读取数据包;
//参数2 A attachment:异步Channel携带的附件,通知回调的时候作为入参使用。即回调方法的第二个参数
//参数3 CompletionHandler<Integer,? super A>:接收通知回调的业务handler,本例程中为ReadCompletionHandler。
result.read(byteBuffer, byteBuffer, new ReadCompleteHandler(result));
}
@Override
public void failed(Throwable exc, SocketServiceCb attachment) {
}
}
class ReadCompleteHandler implements CompletionHandler<Integer, ByteBuffer> {
private AsynchronousSocketChannel channel;
public ReadCompleteHandler(AsynchronousSocketChannel result) {
this.channel = result;
}
@Override
public void completed(Integer result, ByteBuffer attachment) {
//flip操作,为后续从缓冲区读取数据做准备
System.out.print("数据大小为:"+attachmen