Netty学习之路(三)-AIO编程

NIO 2.0引入了新的异步通道的概念,与之前非阻塞IO(NIO)不同的是,NIO 2.0异步套接字通道是真正的异步非阻塞I/O,对应于UNIX网络编程中的事件驱动I/O(AIO)。它不需要通过多路复用器对注册的通道进行轮询操作即可实现异步读写,从而简化了NIO的编程模型。话不多说,直接代码实践。

AIO服务端

package com.ph.AIO;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
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;

/**
 * Create by PH on 2018/11/3 
 */
public class AIOServer {

    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) {
                //采用默认值
            }
        }
        //启用服务端线程
        new Thread(new AsyncServer(port), "server-01").start();
    }
}

class AsyncServer implements Runnable {

    private int port;
    CountDownLatch latch;
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncServer(int port) {
        this.port = port;
        try {
            // 创建一个异步服务端通道
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            // 绑定监听端口
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The server is start in port :" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try {
            //让线程在此阻塞,防止服务端执行完成退出
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void doAccept() {
        //第一个参数为服务端对象,第二个参数是回调对象
        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
    }
}

class AcceptCompletionHandler implements CompletionHandler {

    /**
     * 新的客户端接入成功后调用
     */
    public void completed(AsynchronousSocketChannel result, AsyncServer attachment) {
        //继续接受其他客户端连接
        attachment.asynchronousServerSocketChannel.accept(attachment, this);
        //预分配1M缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //第一个参数为接受缓冲区,用于从异步Channel读取数据包
        //回调时的参数
        //回调对象
        result.read(buffer, buffer, new ReadCompletionHandler(result));
    }

    /**
     * 新客户端接入失败后调用
     * @param exc
     * @param attachment
     */
    public void failed(Throwable exc, AsyncServer attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
}

class ReadCompletionHandler implements CompletionHandler {

    private AsynchronousSocketChannel channel;

    public ReadCompletionHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    public void completed(Integer result, ByteBuffer attachment) {
        //将limit置为position,position置为0
        attachment.flip();
        //remaining()返回limit - position,即可读字节长度
        byte[] body = new byte[attachment.remaining()];
        //将缓冲区数据读到body中
        attachment.get(body);
        try {
            String req = new String(body, "UTF-8");
            System.out.println("Server receive :" + req);
            //向客户端发送消息
            doWrite("Server message");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    private void doWrite(String msg) {
        if(msg != null && msg.trim().length()>0){
            byte[] bytes = msg.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            //与read的参数类似
            channel.write(writeBuffer, writeBuffer, new CompletionHandler() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    //如果没有发送完成,继续发送
                    if(attachment.hasRemaining()) {
                        channel.write(attachment, attachment, this);
                    }
                }

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

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

AIO客户端

package com.ph.AIO;

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;

/**
 * Create by PH on 2018/11/3
 */
public class AIOClient {
    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) {
                //采用默认值
            }
        }
        //启用服务端线程
        new Thread(new AsyncClient("127.0.0.1",port), "Client-01").start();
    }
}

class AsyncClient implements CompletionHandler, Runnable {

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

    public AsyncClient(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            client = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        latch = new CountDownLatch(1);
        client.connect(new InetSocketAddress(host, port), this, this);
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void failed(Throwable exc, AsyncClient attachment) {
        try {
            this.client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void completed(Void result, AsyncClient asyncClient) {
        byte[] req = "CLIENT TEST".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        //向服务端发送消息
        client.write(writeBuffer, writeBuffer, new CompletionHandler() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                //如果没有发送完继续发送,反之则等待接受服务端消息
                if (attachment.hasRemaining()) {
                    client.write(attachment, attachment, this);
                } else {
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    client.read(readBuffer, readBuffer, new CompletionHandler() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            attachment.flip();
                            byte[] bytes = new byte[attachment.remaining()];
                            attachment.get(bytes);
                            String body;
                            try {
                                body = new String(bytes, "UTF-8");
                                System.out.println("Client receive :" + body);
                                latch.countDown();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }

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

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


}

你可能感兴趣的:(Netty)