JDK AIO编程

NIO2.0引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。异步通道提供两种方式获取获取操做结果。java

  1. 经过java.util.concurrent.Future类来表示异步操做的结果;
  2. 在执行异步操做的时候传入一个java.nio.channels。

CompletionHandler接口的实现类做为操做完成的回调。编程

NIO2.0的异步套接字通道是真正的异步非阻塞I/O,它对应UNIX网络编程中的事件驱动I/O(AIO),它不须要经过多路复用器(Selector)对注册的通道进行轮询操做便可实现异步读写,从而简化了NIO的编程模型。数组

服务端代码示例:

import java.io.IOException;

public class TimeServer {

    public static void main(String[] args) throws IOException {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        //首先建立异步的时间服务器处理类,而后启动线程将AsyncTimeServerHandler启动
        AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(port);
        new Thread(timeServer, "AIO-AsyncTimeServerHandler-001").start();
    }
}


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


public class AsyncTimeServerHandler implements Runnable {


    CountDownLatch latch;
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port) {
        //在构造方法中,咱们首先建立一个异步的服务端通道AsynchronousServerSocketChannel,
        //而后调用它的bind方法绑定监听端口,若是端口合法且没被占用,绑定成功,打印启动成功提示到控制台。
        try {
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time server is start in port : " + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //在线程的run方法中,初始化CountDownLatch对象,
        //它的做用是在完成一组正在执行的操做以前,容许当前的线程一直阻塞。
        //在本例程中,咱们让线程在此阻塞,防止服务端执行完成退出。
        //在实际项目应用中,不须要启动独立的线程来处理AsynchronousServerSocketChannel,这里仅仅是个demo演示。
        latch = new CountDownLatch(1);
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //用于接收客户端的链接,因为是异步操做,
    //咱们能够传递一个CompletionHandler<AsynchronousSocketChannel,? super A>类型的handler实例接收accept操做成功的通知消息,
    //在本例程中咱们经过AcceptCompletionHandler实例做为handler来接收通知消息,
    public void doAccept() {
        asynchronousServerSocketChannel.accept(this, new CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler>() {
            @Override
            public void completed(AsynchronousSocketChannel result,
                                  AsyncTimeServerHandler attachment) {
                //咱们从attachment获取成员变量AsynchronousServerSocketChannel,而后继续调用它的accept方法。
                //在此可能会心存疑惑:既然已经接收客户端成功了,为何还要再次调用accept方法呢?
                //缘由是这样的:当咱们调用AsynchronousServerSocketChannel的accept方法后,
                //若是有新的客户端链接接入,系统将回调咱们传入的CompletionHandler实例的completed方法,
                //表示新的客户端已经接入成功,由于一个AsynchronousServerSocket Channel能够接收成千上万个客户端,
                //因此咱们须要继续调用它的accept方法,接收其余的客户端链接,最终造成一个循环。
                //每当接收一个客户读链接成功以后,再异步接收新的客户端链接。
                attachment.asynchronousServerSocketChannel.accept(attachment, this);
                //链路创建成功以后,服务端须要接收客户端的请求消息,
                //建立新的ByteBuffer,预分配1M的缓冲区。
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                //经过调用AsynchronousSocketChannel的read方法进行异步读操做。
                //下面咱们看看异步read方法的参数。
                //ByteBuffer dst:接收缓冲区,用于从异步Channel中读取数据包;
                //A attachment:异步Channel携带的附件,通知回调的时候做为入参使用;
                //CompletionHandler<Integer,? super A>:接收通知回调的业务handler,本例程中为ReadCompletionHandler。
                result.read(buffer, buffer, new ReadCompletionHandler(result));
            }

            @Override
            public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
                exc.printStackTrace();
                attachment.latch.countDown();
            }
        });
    }

}

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel channel;

    public ReadCompletionHandler(AsynchronousSocketChannel channel) {
        //将AsynchronousSocketChannel经过参数传递到ReadCompletion Handler中看成成员变量来使用
        //主要用于读取半包消息和发送应答。本例程不对半包读写进行具体说明
        if (this.channel == null)
            this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        //读取到消息后的处理,首先对attachment进行flip操做,为后续从缓冲区读取数据作准备。
        attachment.flip();
        //根据缓冲区的可读字节数建立byte数组
        byte[] body = new byte[attachment.remaining()];
        attachment.get(body);
        try {
            //经过new String方法建立请求消息,对请求消息进行判断,
            //若是是"QUERY TIME ORDER"则获取当前系统服务器的时间,
            String req = new String(body, "UTF-8");
            System.out.println("The time server receive order : " + req);
            String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req) ? new java.util.Date(
                    System.currentTimeMillis()).toString() : "BAD ORDER";
            //调用doWrite方法发送给客户端。
            doWrite(currentTime);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void doWrite(String currentTime) {
        if (currentTime != null && currentTime.trim().length() > 0) {
            //首先对当前时间进行合法性校验,若是合法,调用字符串的解码方法将应答消息编码成字节数组,
            //而后将它复制到发送缓冲区writeBuffer中,
            byte[] bytes = (currentTime).getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            //最后调用AsynchronousSocketChannel的异步write方法。
            //正如前面介绍的异步read方法同样,它也有三个与read方法相同的参数,
            //在本例程中咱们直接实现write方法的异步回调接口CompletionHandler。
            channel.write(writeBuffer, writeBuffer,
                    new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer buffer) {
                            //对发送的writeBuffer进行判断,若是还有剩余的字节可写,说明没有发送完成,须要继续发送,直到发送成功。
                            if (buffer.hasRemaining())
                                channel.write(buffer, buffer, this);
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            //关注下failed方法,它的实现很简单,就是当发生异常的时候,对异常Throwable进行判断,
                            //若是是I/O异常,就关闭链路,释放资源,
                            //若是是其余异常,按照业务本身的逻辑进行处理,若是没有发送完成,继续发送.
                            //本例程做为简单demo,没有对异常进行分类判断,只要发生了读写异常,就关闭链路,释放资源。
                            try {
                                channel.close();
                            } catch (IOException e) {
                                // ingnore on close
                            }
                        }
                    });
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端代码示例:

public class TimeClient {

    public static void main(String[] args) {
        int port = 8080;
        //经过一个独立的I/O线程建立异步时间服务器客户端handler,
        //在实际项目中,咱们不须要独立的线程建立异步链接对象,由于底层都是经过JDK的系统回调实现的.
        new Thread(new AsyncTimeClientHandler("127.0.0.1", port), "AIO-AsyncTimeClientHandler-001").start();
    }
}

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeClientHandler implements CompletionHandler<Void, AsyncTimeClientHandler>, Runnable {

    private AsynchronousSocketChannel client;
    private String host;
    private int port;
    private CountDownLatch latch;

    //首先经过AsynchronousSocketChannel的open方法建立一个新的AsynchronousSocketChannel对象。
    public AsyncTimeClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            client = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        //建立CountDownLatch进行等待,防止异步操做没有执行完成线程就退出。
        latch = new CountDownLatch(1);
        //经过connect方法发起异步操做,它有两个参数,
        //A attachment:AsynchronousSocketChannel的附件,用于回调通知时做为入参被传递,调用者能够自定义;
        //CompletionHandler<Void,? super A> handler:异步操做回调通知接口,由调用者实现。
        client.connect(new InetSocketAddress(host, port), this, this);
        try {
            latch.await();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //异步链接成功以后的方法回调——completed方法
    @Override
    public void completed(Void result, AsyncTimeClientHandler attachment) {
        //建立请求消息体,对其进行编码,而后复制到发送缓冲区writeBuffer中,
        //调用Asynchronous SocketChannel的write方法进行异步写。
        //与服务端相似,咱们能够实现CompletionHandler <Integer, ByteBuffer>接口用于写操做完成后的回调。
        byte[] req = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        client.write(writeBuffer, writeBuffer,
                new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer buffer) {
                        //若是发送缓冲区中仍有还没有发送的字节,将继续异步发送,若是已经发送完成,则执行异步读取操做。
                        if (buffer.hasRemaining()) {
                            client.write(buffer, buffer, this);
                        } else {
                            //客户端异步读取时间服务器服务端应答消息的处理逻辑
                            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                            //调用AsynchronousSocketChannel的read方法异步读取服务端的响应消息。
                            //因为read操做是异步的,因此咱们经过内部匿名类实现CompletionHandler<Integer,ByteBuffer>接口,
                            //当读取完成被JDK回调时,构造应答消息。
                 client.read(readBuffer,readBuffer, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result,ByteBuffer buffer) { //从CompletionHandler的ByteBuffer中读取应答消息,而后打印结果。 buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String body; try { body = new String(bytes,"UTF-8"); System.out.println("Now is : " + body); latch.countDown(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { //当读取发生异常时,关闭链路, //同时调用CountDownLatch的countDown方法让AsyncTimeClientHandler线程执行完毕,客户端退出执行。 try { client.close(); latch.countDown(); } catch (IOException e) { // ingnore on close } } }); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { client.close(); latch.countDown(); } catch (IOException e) { // ingnore on close } } }); } @Override public void failed(Throwable exc, AsyncTimeClientHandler attachment) { exc.printStackTrace(); try { client.close(); latch.countDown(); } catch (IOException e) { e.printStackTrace(); } } }

须要指出的是,正如以前的NIO例程,咱们并无完整的处理网络的半包读写,在对例程进行功能测试的时候没有问题,可是,若是对代码稍加改造,进行压力或者性能测试,就会发现输出结果存在问题。服务器

经过打印线程堆栈的方式看下JDK回调异步Channel CompletionHandler的调用状况:网络

从“Thread-2”线程堆栈中能够发现,JDK底层经过线程池ThreadPoolExecutor来执行回调通知,异步回调通知类由sun.nio.ch.AsynchronousChannelGroupImpl实现,它通过层层调用,最终回调com.phei.netty.aio.AsyncTimeClientHandler$1.completed方法,完成回调通知。异步

由此咱们也能够得出结论:异步SocketChannel是被动执行对象,咱们不须要像NIO编程那样建立一个独立的I/O线程来处理读写操做。对于AsynchronousServerSocketChannel和AsynchronousSocketChannel,它们都由JDK底层的线程池负责回调并驱动读写操做async

正由于如此,基于NIO2.0新的异步非阻塞Channel进行编程比NIO编程更为简单。ide

相关文章
相关标签/搜索