NIO在网络编程的应用 (出自netty权威指南)

ServerSocketChannel
SocketChannel
Selector
在这里插入图片描述
代码示例(TimeServer)

//channel()方法: Returns the channel for which this key was created.
//This method will continue to return the channel even after the key
//is cancelled.

分析在代码中


19年11月30日再次思考 个人见解: 1. 服务端创建了个selector,然后给serverSocket注册用于监听ACCEPT,每1s轮询,当有用户端成功连进来,即isAcceptable()==true,此时就给这个SocketChannel注册READ。在selector中既有serverSocket的监听ACCEPT,也有SocketChannel的READ。当轮询到SocketChannel时有写入,就进入isReadable()条件,进行具体操作。循环上述过程。 2. 客户端创建了selector,然后进行TCP连接。如果失败,给SocketChannel注册进行监听Connect,如果TCP3次握手成功,则注册监听READ,每过1s轮询。重复上述过程。selector里面可能有READ,也可能有CONNECT
package com.NIOtext;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class TimeServer {
    public static void main(String...args){
        int port = 8080;
        MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
        new Thread(timeServer,"NIO-001").start();
           }
}
class MultiplexerTimeServer implements Runnable{
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop;
    public MultiplexerTimeServer(int port){
        try{
            //打开ServerSocketChannel,用于监听客户端的连接,它是所有客户端连接的父管道
            serverSocketChannel = ServerSocketChannel.open();
            //绑定监听窗口,设置连接为非阻塞模式
            serverSocketChannel.socket().bind(new InetSocketAddress(port),1024);
            serverSocketChannel.configureBlocking(false);

            selector = Selector.open();
            //将ServerSocketChannel注册到多路复用器上监听Accept事件
            //SelectionKey.OP_CONNECT
            //SelectionKey.OP_ACCEPT
            //SelectionKey.OP_READ
            //SelectionKey.OP_WRITE
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("The time server is start in port :"+port);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }
    public void stop(){
        this.stop = true;
    }

    @Override
    public void run() {
        //无限轮询准备就绪的selectionKey
        while(!stop){
            try{
                selector.select(1000);//每隔一秒被唤醒一次
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectedKeys.iterator();
                SelectionKey key = null;
                while(it.hasNext()){
                    key = it.next();
                    it.remove();
                    try{
                        handleInput(key);
                    }catch (Exception e) {
                        if (key != null) {
                            key.cancel();
                            if (key.channel() != null) {
                                key.channel().close();
                            }
                        }
                    }
                }
            }catch(Throwable t){
                t.printStackTrace();
            }
        }
        //多路复用器关闭后所有注册在上面的Channel和pipe都被自动注册与关闭,不需要重复释放资源
        if(selector!=null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()) {
            //通道触发了一个事件意思是该事件已经就绪
            //ServerSocketChannel 准备好接收新进入的连接称为”接收就绪“。
            if (key.isAcceptable()) {
                //channel()方法  Returns the channel for which this key was created.
                //This method will continue to return the channel even after the key is cancelled.
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();//接受客户端连接请求
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);//监听read操作
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("The time server receive order :" + body);
                    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                    doWrite(sc, currentTime);
                } else if (readBytes < 0) {
                    key.cancel();//selectionKey手动关闭 remove() 或cancel()
                    sc.close();
                } else {
                    ;
                }
            }
        }
    }
    private void doWrite(SocketChannel channel,String response) throws IOException{
        if(response!=null && response.trim().length()>0){
            byte[]bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();//在write之前必须写
            channel.write(writeBuffer);
        }
    }
}

在这里插入图片描述
客户端代码示例(TimeClient)
和服务器差不多
连接,在doConnect()方法中连接失败时设置OP_CONNECT,在轮询时准备就绪,继续往下进行

package com.NIOtext;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class TimeClientHandle implements Runnable {
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;
    public static void main(String...args){
        int port = 8080;
        new Thread(new TimeClientHandle("127.0.0.1",port),"TimeClient-001").start();
    }
    public TimeClientHandle(String host,int port){
        this.host = host == null?"127.0.0.1":host;
        this.port = port;
        try{
            selector = Selector.open();
            //打开socketChannel
            socketChannel = SocketChannel.open();
            //设置非阻塞
            socketChannel.configureBlocking(false);
        }catch(IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try{
            doConnect();
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
        while(!stop){
            try{
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while(it.hasNext()){
                    key = it.next();
                    it.remove();
                    try{
                        handleInput(key);
                    }catch (Exception e){
                        if(key!=null){
                            key.cancel();
                            if(key.channel()!=null){
                                key.channel().close();
                            }
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
                System.exit(1);
            }
        }
        if(selector!=null){
            try{
                selector.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    private void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()){
            SocketChannel sc = (SocketChannel)key.channel();
            if(key.isConnectable()){
                if(sc.finishConnect()){
                    sc.register(selector,SelectionKey.OP_READ);
                    doWrite(sc);
                }else
                    System.exit(1);
            }
            if(key.isReadable()){
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if(readBytes>0){
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes,"UTF-8");
                    System.out.println("Now is : "+body);
                    this.stop = true;
                }else if(readBytes<0){
                    key.channel();
                    sc.close();
                }else
                    ;

            }
        }
    }
    private void doConnect() throws IOException{
        //设置TCP参数
        //连接成功 注册read
        //连接失败 注册connect
        if(socketChannel.connect(new InetSocketAddress(host,port))){
            socketChannel.register(selector,SelectionKey.OP_READ);
            doWrite(socketChannel);
        }else
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
    }
    private void doWrite(SocketChannel sc) throws IOException{
        byte[]req = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        //向socketChannel写入信息
        sc.write(writeBuffer);
        if(!writeBuffer.hasRemaining())
            System.out.println("Send order 2 server succeed.");
    }
}


AIO
import java.io.IOException;

public class TimeServer {
    public static void main(String...args) throws IOException {
        int port = 8080;
        //异步的时间服务器处理类
        AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(port);
        //        new Thread(timeServer,"AIO-1").start();
        //AIO是不需要再用一个线程处理,可以像下面一样
        timeServer.run();
    }
}
/*
The time server is start in port:8080
The time server receive order:QUERY TIME ORDER
The time server receive order:QUERY TIME ORDER
The time server receive order:QUERY TIME ORDER
...
*/
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;
//时间服务器处理类
public class AsyncTimeServerHandler implements Runnable {
    private int port;
    CountDownLatch latch;
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port){
        this.port = port;
        try {
            //1.创建异步的服务端通道
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            //2.绑定服务端端口
            /*绑定成功打印文字*/
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
        System.out.println("The time server is start in port:"+port);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //run方法只是用于演示,可以不用创建新线程,所以说是异步创建
    @Override
    public void run() {
        /*完成一组操作前允许当前线程阻塞,防止服务端执行完成退出*/
        latch = new CountDownLatch(1);
        doAccept();
        try{
            latch.await();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    //当客户端连接成功之后就会回调传入的Handler的completed来实现异步接收连接
    //当客户端连接失败后会调用Handler中的failed()方法
    //nio的accept()方法是不阻塞的,与serverSocket.accept()不同
    public void doAccept(){
        asynchronousServerSocketChannel.accept(this,new AcceptCompletionHandler());
        System.out.println("accept() 不阻塞");
    }
}
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
//处理通知信息
public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,AsyncTimeServerHandler> {

    //AsynchronousSocketChannel,AsyncTimeServerHandler
    //void completed​(V result, A attachment)
    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        attachment.asynchronousServerSocketChannel.accept(attachment,this);
        System.out.println("accept() 不阻塞");
        //预分配1M的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //异步读操作
        /*3个参数:
        * 1.ByteBuffer dst 接收缓冲区,用于异步Channel中读取数据包
        * 2.A attachment 异步Channel携带的附件,通知回调时作为入参使用
        * 3.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){
        if(this.channel == null){
            this.channel=channel;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        /*将attachment的信息写入body*/
        byte[]body = new byte[attachment.remaining()];
        attachment.get(body);
        try{
            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(currentTime);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    }
    public void doWrite(String currentTime){
        /*trim()去掉首位空格*/
        if(currentTime!=null&&currentTime.trim().length()>0){
            byte []bytes = (currentTime).getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            /*调用异步写方法*/
            channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer buffer) {
                    /*如果还有剩余字节,说明发送失败,需要继续发送*/
                    if (buffer.hasRemaining())
                        channel.write(buffer, buffer, this);
                }

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

    @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){
        //实际项目中不需要独立线程创建异步对象
        //new Thread(new AsyncTimeClientHandler("127.0.0.1",8080)).start();
        new AsyncTimeClientHandler("127.0.0.1",8080).run();
    }
}

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;

    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() {
        latch = new CountDownLatch(1);
        //调用connect发起异步操作
        /*
        * 两个参数 A attachment ,AsynchronousSocketChannel附件 回调通知时作为入参
        * CompletionHandler<Void,? super A> 异步操作回调通知接口*/
        client.connect(new InetSocketAddress(host, port), this, this);
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void completed(Void result, AsyncTimeClientHandler attachment) {
        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);
                            client.read(
                                    readBuffer, readBuffer,
                                    new CompletionHandler<Integer, ByteBuffer>() {
                                        @Override
                                        public void completed(Integer result, ByteBuffer buffer) {
                                            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) {
                                            try {
                                                client.close();
                                                latch.countDown();
                                            } catch (IOException e) {
                                                //
                                            }
                                        }
                                    });
                        }
                    }

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

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

(未完待续)

发布了23 篇原创文章 · 获赞 4 · 访问量 833

猜你喜欢

转载自blog.csdn.net/qq_43656529/article/details/102963408