NIO

NIO编程

简介:
与Socket和ServerSocket类相对应,NIO提供了SocketChannel和ServerSocketChannel两种不同的套接字通道实现,这两种新增的通道都支持阻塞和非阻塞两种模式。
一般来说低负载,低并发的应用可以采用同步阻塞模式以降低编程的复杂度,但是对于高负载,高并发的应用需要使用NIO的非阻塞模式开发详情参见
mmap原理解析
优点:
nio 模式最大化压榨了CPU,把时间片更好利用起来

NIO类库简介:
NIO是在JDK1.4中引入的为了弥补同步阻塞I/O的不足,它在标准java代码中提供了高速的,面向块的I/O,通过定义包含数据的类,以及通过以块的形式来处理这些数据

NIO类库简介:
缓冲区 Buffer
在面向流的I/O中是将数据直接读/写到Stream对象中的,但是在NIO中任何时候访问数据都是都是通过缓冲区进行操作的,在读数据时,它是先读取到缓冲区,写数据时先写到缓冲区。它的本质是一个数组,每一种java类型(除了Boolean)都对应一种缓冲区,具体如下:

 - ByteBuffer:字节缓冲区
 - CharBuffer:字符缓冲区
 - ShortBuffer:短整型缓冲区
 - IntBuffer:整形缓冲区
 - LongBuffer:长整型缓冲区
 - FloatBuffer:浮点型缓冲区
 - DoubleBuffer:双精度浮点型缓冲区

缓冲区的类图继承关系:
这里写图片描述

通道 Channel
Channel是一个通道,通过它可以读取和写入数据,它就像自来水管一样。它与流的不同之处在于它是双向的,而流只能在一个方向上移动。同时它是全双工的支持同时进行读写操作
缓冲区的类图继承关系:
这里写图片描述
前三层主要是Channel接口用于定义它的接口,下面就是一些具体的功能实现(抽象类),实际上Channel主要分为两大类:一类是用于读写网络数据的SelectableChannel,一类是用于读写文件的FileChannel,其中SocketChannel和ServerSocketChannel都是SelectableChannel的子类

多路复用器 Selector
它是NIO编程的基础,Selector会不断被轮询注册在其上的Channel,如果某个Channel上面有新的TCP连接接入,读和写事件,这个Channel就处于就绪的状态,会被 Selector轮询出来,然后通过SelectionKey可以获取就绪的Channel集合,然后进行I/O操作。一个多路复用Selector可以同时轮询多个Channel,由于JDK使用的是epoll代替传统的select实现,所以他没有最大连接句柄的限制1024/2048的限制,也就意味着一个线程负责Selector的轮询,就可以接入成千上万的客户端

NIO服务端序列图:
这里写图片描述

步骤一:打开ServerSocketChannel,用于监听客户端的连接,他是多有客户端连接的父通道,代码如下:

ServerSocketChannel acceptSvr = ServerSocketChannel.open();

步骤二:绑定监听的端口,设置连接为非阻塞模式,代码如下:

Integer port = 8080;
ServerSocketChannel acceptSvr = ServerSocketChannel.open();
acceptSvr.socket().bind(new InetSocketAddress(InetAddress.getByName("IP"), port));
acceptSvr.configureBlocking(false);

步骤三:创建Reactor线程,创建多路复用器并启动线程,代码如下:

Selector selector = Selector.open();
new Thread(new ReactorTask()).start();

步骤四:将ServerSocketChannel 注册到Reactor线程的多路复用器Selector 上,监听Accept事件,代码如下:

SelectionKey selectionKey = acceptSvr.register(selector, SelectionKey.OP_ACCEPT, ioHandler);

步骤五:多路复用器在线程的run方法无限循环体内轮询准备就绪的key,代码如下:

int num = selector.select();
Set selectionKeys = selector.selectedKeys();
Iterator it = selectionKeys.iterator();
while (it.hasNext()) {
   SelectionKey key = (SelectionKey)it.next();
   // deal with i/o event
}

步骤六:多路复用器监听到有新的客户端接入,处理新的请求接入,完成TCP三次握手,建立物理连接,代码如下:

SocketChannel channel = acceptSvr.accept();

步骤七:设置客户端连接为阻塞模式,代码如下:

channel.configureBlocking(false);
channel.socket().setReuseAddress(true);

步骤八:将新接入的客户端连接注册到Reactor线程的多路复用器上,监听读操作,用来读取客户端发送来数据,代码如下:

SelectionKey Key = channel.register(selector, SelectionKey.OP_ACCEPT, ioHandler);

步骤九:异步读取客户端请求消息到缓冲区,代码如下:

int readNum = channel.read(receivedBuffer);

步骤十:对ByteBuffer进行编码,如果有半包消息指针则reset,继续读取后续报文,将解码成功的消息封装成Task,投递到业务线程池中,进行业务逻辑操作,代码如下:

Object message = null;
while (buffer.hasRemain()) {
    byteBuffer.mark();
    message = decode(byteBuffer);
    if (message == null) {
         byteBuffer.reset();
         break;
    }
    messageList.add(message);
}
if (!byteBuffer.hasRemain()) {
   byteBuffer.clear();
} else {
   byteBuffer.compact();
}
if (messageList != null && !messageList.isEmpty()) {
    for (Object msg : messageList) {
        handlerTask(msg);
    }
}

步骤十一:将POJO对象encode成ByteBuffer,调用SocketChannel的异步write接口,将消息异步发送个客户端,代码如下:

channel.write(buffer);

注意:如果发送去TCP缓冲区满了,会导致写半包,此时需要注册监听写操作位,循环写,知道整包消息写入TCP缓冲区

Server端代码demo:

package com.tianlh.nio;

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;

/**
 *
 * @author wb-tianlihui
 * @date 2017/12/11
 */
public class MultiplexerTimeServer implements Runnable {
    private Selector selector;
    private ServerSocketChannel servChannel;
    private volatile boolean stop;

    /**
     * 初始化多路复用器、绑定监听端口
     * @param port
     */
    public MultiplexerTimeServer(int port) {
        try {
            selector = Selector.open();
            servChannel = ServerSocketChannel.open();
            servChannel.configureBlocking(false);
            servChannel.socket().bind(new InetSocketAddress(port));
            // 在selector上注册一个接收事件,当可以接收时就会触发该事件
            servChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("The time server is start in port:" + port);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        //用一个线程来轮行selector上面各个channel的事件状态
        //当时数据可读时这个线程才过来读/写数据,不存在阻塞等待
        //由于都是一个线程来完成不存在上线文切换,可以节约资源和提高性能
        //针对多核cpu当有数据可读/写时当然也可以才用线程池来(线程数 = 核心数)并行读写,性能会更高
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key;
                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();
            }
        }
        if (selector != null) {
            try {
                selector.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey key) throws IOException {

        if (key.isValid()) {
            // 处理新接入的请求,将对应的非阻塞SocketChannel注册到selector上,来监听读就绪事件
            // 当下次 selector.select 时来通过isReadable检查该SocketChannel是否可读了,可读则开始读取数据,
            // 这个阶段是使用户线程来操作的(AIO这个阶段是有操作系统帮忙完成的,完成后才通知用户线程)阻塞的,
            // 但性能非常高,可以采用线程池来操作 网卡 --> 内存 --> 用户空间
            if (key.isAcceptable()) {
                ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_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();
                    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();
            channel.write(writeBuffer);
        }

    }
}

NIO服客户端序列图:
这里写图片描述

代码demo:

package com.tianlh.nio;

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;

/**
 *
 * @author wb-tianlihui
 * @date 2017/12/11
 */
public class TimeClientHandle implements Runnable {
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    public TimeClientHandle(String host, int port) {
        this.host = host == null ? "127.0.0.1" : host;
        this.port = port;
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try {
            doConnect();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key;
                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);
            }
        }
        // 多路复用器关闭后,所有注册在上面的Channel和Pipe等资源都会被自动去注册关闭,
        // 所以不需要重复释放资源
        if (selector != null) {
            try {
                selector.close();
            } catch (Exception 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.cancel();
                    sc.close();
                } else {
                    ;
                }
            }
        }
    }

    private void doConnect() throws IOException {
        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 = "HELLO NIO SERVER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        sc.write(writeBuffer);
        if (!writeBuffer.hasRemaining()) {
            System.out.println("Send data succeed.");
        }
    }
}
package com.tianlh.nio;

/**
 *
 * @author wb-tianlihui
 * @date 2017/12/11
 */
public class Bootstrap {
    public static void main(String[] args) throws InterruptedException {
        new Thread(new MultiplexerTimeServer(8080)).start();
        Thread.sleep(5000L);
        new Thread(new TimeClientHandle("127.0.0.1", 8080)).start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值