您的位置 首页 java

面试官:NIO非阻塞网络编程原理了解吗?一文深度讲解避坑

NIO非阻塞网络编程原理

1、NIO基本介绍

  1. Java NIO 全称 Java non-blocking IO,是指 JDK 提供的新 API。从 JDK1.4 开始,Java 提供了一系列改进的
    输入/输出的新特性,被统称为 NIO(即 New IO),是同步非阻塞的。
  2. NIO 相关类都被放在 java.nio 包及子包下,并且对原 java.io 包中的很多类进行改写。【基本案例】
  3. NIO 有三大核心部分: channel ( 通道) , buffer ( 缓冲区) , Selector( 选择器)
  4. N IO 是 是 区 面向 缓冲区 ,或者面向块编程。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络。
  5. Java NIO 的非阻塞模式,使一个 线程 从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而 不是保持线程阻塞 ,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。 非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情。
  6. 通俗理解:NIO 是可以做到用一个线程来处理多个操作的。假设有 10000 个请求过来,根据实际情况,可以分配50 或者 100 个线程来处理。不像之前的阻塞 IO 那样,非得分配 10000 个。
  7. HTTP2.0 使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数量比 HTTP1.1 大了好几个数量级。

2、NIO与BIO的比较

  1. BIO 以流的方式处理数据,而 NIO 以块的方式处理数据,块 I/O 的效率比流 I/O 高很多
  2. BIO 是阻塞的,NIO 则是非阻塞的
  3. BIO 基于字节流和字符流进行操作,而 NIO 基于 Channel(通道)和 Buffer(缓冲区)进行操作,数据总是从通道
    读取到缓冲区中,或者从缓冲区写入到通道中。Selector(选择器)用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道

3、NIO三大核心原理示意图

NIO中的三个核心分别是Selector、Channel、Buffer,他们之间的关系如下图:

三大核心组件介绍:

4、缓冲区(Buffer)

基本介绍

缓冲区(Buffer):缓冲区本质上是一个 可以读写数据的内存块,可以理解成是一个 容器对象( 含数组),该对象提供了一组方法,可以更轻松地使用内存块,,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer。

Buffer 类及其子类

1)在 NIO 中,Buffer 是一个顶层父类,它是一个抽象类, 类的层级关系图:

2)Buffer 类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息:

 private int mark = -1;
private int position = 0;
private int limit;
private int capacity;
  

属性解释:

属性

含义

mark

标记作用 ,buffer.position(0).mark()进行标记,buffer.reset();就会回到刚刚的标记位置

position

下一个要被读取或者要被写入位置的 索引 ,每次读写之后都会自动变换位置

limit

极限 ,例如容量是10的buffer,但limit设置为5的话,没法对5后面的数据进行操作

capacity

buffer 容量

ByteBuffer

Buffer类中一些常用方法

 public abstract class Buffer {
    //JDK1.4时,引入的api
    public final int capacity( )//返回此缓冲区的容量
    public final int position( )//返回此缓冲区的位置
    public final Buffer position (int newPositio)//设置此缓冲区的位置
    public final int limit( )//返回此缓冲区的限制
    public final Buffer limit (int newLimit)//设置此缓冲区的限制
    public final Buffer mark( )//在此缓冲区的位置设置标记
    public final Buffer reset( )//将此缓冲区的位置重置为以前标记的位置
    public final Buffer clear( )//清除此缓冲区, 即将各个标记恢复到初始状态,但是数据并没有真正擦除, 后面操作会覆盖
    public final Buffer flip( )//反转此缓冲区
    public final Buffer rewind( )//重绕此缓冲区
    public final int remaining( )//返回当前位置与限制之间的元素数
    public final boolean hasRemaining( )//告知在当前位置和限制之间是否有元素
    public abstract boolean isReadOnly( );//告知此缓冲区是否为只读缓冲区
    //JDK1.6时引入的api
    public abstract boolean hasArray();//告知此缓冲区是否具有可访问的底层实现数组
    public abstract Object array();//返回此缓冲区的底层实现数组
    public abstract int arrayOffset();//返回此缓冲区的底层实现数组中第一个缓冲区元素的偏移量
    public abstract boolean isDirect();//告知此缓冲区是否为直接缓冲区
}
  

5、通道(Channel)

基本介绍

1)、NIO 的通道类似于流,但有些区别如下:

通道可以同时进行读写,而流只能读或者只能写
通道可以实现异步读写数据
通道可以从缓冲读数据,也可以写数据到缓冲:

2)、BIO 中的 stream 是单向的,例如 FileInputStream 对象只能进行读取数据的操作,而 NIO 中的通道(Channel)
是双向的,可以读操作,也可以写操作。

3)、 Channel 在 NIO 中是一个接口 public interface Channel extends Closeable{}
4)、 常 用 的 Channel 类 有 : FileChannel 、 DatagramChannel 、 Server Socket Channel 和 SocketChannel 。 ServerSocketChanne 类似 ServerSocket , SocketChannel 类似 Socket

  1. 、FileChannel 用于文件的数据读写,DatagramChannel 用于 UDP 的数据读写,ServerSocketChannel 和
    SocketChannel 用于 TCP 的数据读写。

6)、 图示

面试官:NIO非阻塞网络编程原理了解吗?一文深度讲解避坑

6、Channel基本介绍

FileChannel 类

FileChannel 主要用来对本地文件进行 IO 操作,常见的方法有

  1. public int read(ByteBuffer dst) ,从通道读取数据并放到缓冲区中
  2. public int write(ByteBuffer src) ,把缓冲区的数据写到通道中
  3. public long transferFrom(ReadableByteChannel src, long position, long count),从目标通道中复制数据到当前通道
  4. public long transferTo(long position, long count, WritableByteChannel target),把数据从当前通道复制给目标通道

关于 Buffer 和 Channel 的注意事项和细节

ByteBuffer 支持类型化的 put 和 get, put 放入的是什么数据类型,get 就应该使用相应的数据类型来取出,否
则可能有 BufferUnderflowException 异常。

7、Selector(选择器)

基本介绍

1)Java 的 NIO,用非阻塞的 IO 方式。可以用一个线程,处理多个的客户端连接,就会使用到 Selector(选择器)

  1. Selector 能够检测多个注册的通道上是否有事件发生(注意:多个 Channel 以事件的方式可以注册到同一个
    Selector),如果有事件发生,便获取事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管
    理多个通道,也就是管理多个连接和请求。
  2. 只有在 连接/通道 真正有读写事件发生时,才会进行读写,就大大地减少了系统开销,并且不必为每个连接都
    创建一个线程,不用去维护多个线程
  3. 避免了多线程之间的上下文切换导致的开销

Selector 示意图和特点说明

面试官:NIO非阻塞网络编程原理了解吗?一文深度讲解避坑

  1. Netty 的 IO 线程 NioEventLoop 聚合了 Selector(选择器,也叫多路复用器),可以同时并发处理成百上千个客
    户端连接。
  2. 当线程从某客户端 Socket 通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。
  3. 线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入和输出
    通道。
  4. 由于读写操作都是非阻塞的,这就可以充分提升 IO 线程的运行效率,避免由于频繁 I/O 阻塞导致的线程挂
    起。
  5. 一个 I/O 线程可以并发处理 N 个客户端连接和读写操作,这从根本上解决了传统同步阻塞 I/O 一连接一线
    程模型,架构的性能、弹性伸缩能力和可靠性都得到了极大的提升

Selector 类相关方法

 public abstract class Selector implements Closeable { 
public static Selector  open ();//得到一个选择器对象
public int select(long timeout);//监控所有注册的通道,当其中有 IO 操作可以进行时,将
对应的 SelectionKey 加入到内部集合中并返回,参数用来设置超时时间
public Set<SelectionKey> selectedKeys();//从内部集合中得到所有的 SelectionKey	
}
  

注意事项

  1. NIO 中的 ServerSocketChannel 功能类似 ServerSocket,SocketChannel 功能类似 Socket
  2. selector 相关方法说明
 selector.select()//阻塞
selector.select(1000);//阻塞 1000 毫秒,在 1000 毫秒后返回
selector.wakeup();//唤醒 selector
selector.selectNow();//不阻塞,立马返还
3.8 NIO 非阻塞  网络编程 原理分析图
  

8、NIO非阻塞网络编程原理分析图

NIO 非阻塞 网络编程相关的(Selector、SelectionKey、Server sc oketChannel 和 SocketChannel) 关系梳理图

关系图:

对上图的说明:

  1. 当客户端连接时,会通过 ServerSocketChannel 得到 SocketChannel
  2. Selector 进行监听 select 方法, 返回有事件发生的通道的个数
  3. 将 socketChannel 注册到 Selector 上, register(Selector sel, int ops), 一个 selector 上可以注册多个 SocketChannel
  4. 注册后返回一个 SelectionKey, 会和该 Selector 关联(集合)
  5. 进一步得到各个 SelectionKey (有事件发生)
  6. 在通过 SelectionKey 反向获取 SocketChannel , 方法 channel()
  7. 可以通过 得到的 channel , 完成业务处理

9、NIO非阻塞网络编程快速入门

  1. 编写一个 NIO 入门案例,实现服务器端和客户端之间的数据简单通讯(非阻塞)
  2. 目的:理解 NIO 非阻塞网络编程机制

服务端:

 public class NIOServer {
    public static void main(String[] args) throws Exception {
        //打开服务器的ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //创建并且打开Selector
        Selector selector = Selector.open();
        //将我们的Socket绑定一个端口,便于客户端连接
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking( false );
        //将ServerSocketChannel注册到selector上
        serverSocketChannel.register(selector, SelectionKey.OP_ accept );
        System.out.println("当前注册的SelectionKey数量:"+selector.keys().size());
        while(true){
            //一直监听,每秒刷新一次,等待客户端的连接
            if (selector.select(1000) == 0){
                System.out.println("服务器等待了1s,无连接");
                continue;
            }
            //通过selector得到selectionKey
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //打印selectionKey数量
            System.out.println("SelectionKey数量:"+selectionKeys.size());
            //通过迭代器遍历所有的selectionKey
             iterator <SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while(selectionKeyIterator.hasNext()){
                //拿到当前的key
                SelectionKey selectionKey = selectionKeyIterator.next();
                if (selectionKey.isAcceptable()){
                    //当确定有selectionKey时,说明必有socketChannel,Server接收后得到SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功,生成一个socketChannel,哈希值:"+socketChannel.hashCode());
                    //将SocketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将其注册到Selector上
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size());
                }
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    channel.read(byteBuffer);
                    //打印一下接到的buffer
                    System.out.println(byteBuffer.toString());
                }
                //手动从集合中移动当前的selectionKey, 防止重复操作
                selectionKeyIterator.remove();
            }
        }
    }
}
  

客户端:

 public class NIOClient {
    public static void main(String[] args) throws Exception{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        if (!socketChannel.connect(inetSocketAddress)) {
            while(!socketChannel.finishConnect()){
                System.out.println("连接需要时间,可以去做其他事情");
            }
        }
        //...如果连接成功,就发送数据
        String str = "hello, Courage";
        //Wraps a byte array into a buffer
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据,将 buffer 数据写入 channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
  

10、SelectionKey

简单介绍:

SelectionKey,表示 Selector 和网络通道的注册关系, 共四种:
int OP_ACCEPT:有新的网络连接可以 accept,值为 16
int OP_CONNECT:代表连接已经建立,值为 8
int OP_READ:代表读操作,值为 1
int OP_WRITE:代表写操作,值为 4
源码中:

 public static final int OP_READ = 1 << 0;
public static final int OP_WRITE = 1 << 2;
public static final int OP_CONNECT = 1 << 3;
public static final int OP_ACCEPT = 1 << 4;
  

SelectionKey 相关方法

 public abstract class SelectionKey {
	public abstract Selector selector();//得到与之关联的 Selector 对象
 	public abstract SelectableChannel channel();//得到与之关联的通道
	public final Object attachment();//得到与之关联的共享数据
 	public abstract SelectionKey interestOps(int ops);//设置或改变监听事件
 	public final boolean isAcceptable();//是否可以 accept
	public final boolean isReadable();//是否可以读
 	public final boolean isWritable();//是否可以写
}
  

11、ServerSocketChannel

基本介绍:

NIO中的 ServerSocketChannel 是一个可以监听新进来的TCP连接的通道, 就像标准IO中的ServerSocket一样。

相关方法:

 public abstract class ServerSocketChannel extends AbstractSelectableChannel  implements NetworkChannel{
    public static ServerSocketChannel open()//得到一个 ServerSocketChannel 通道
    public final ServerSocketChannel bind(SocketAddress local)//设置服务器端端口号
    public final SelectableChannel configureBlocking(boolean block)//设置阻塞或非阻塞模式,															取值 false 表示采用非阻塞模式
    public SocketChannel accept()//接受一个连接,返回代表这个连接的通道对象
    public final SelectionKey register(Selector sel, int ops)//注册一个选择器并设置监听事件
}
  

12、SocketChannel

基本介绍

SocketChannel,网络 IO 通道,具体负责进行读写操作。NIO 把 缓冲区 的数据写入 通道 ,或者把通道里的数
据读到缓冲区。

相关方法

 public abstract class SocketChannel extends
    AbstractSelectableChannel 
    implements ByteChannel, 
    ScatteringByteChannel, 
    GatheringByteChannel,
    NetworkChannel
{
    public static SocketChannel open();//得到一个 SocketChannel 通道
    public final SelectableChannel configureBlocking(boolean block);//设置阻塞或非阻塞模式,取值 false 表示采用非阻塞模式
    public boolean connect(SocketAddress remote);//连接服务器
    public boolean finishConnect();//如果上面的方法连接失败,接下来就要通过该方法完成连接操作
    public int write(ByteBuffer src);//往通道里写数据
    public int read(ByteBuffer dst);//从通道里读数据
    public final SelectionKey register(Selector sel, int ops, Object att);//注册一个选择器并设置监听事件,最后一个参数可以设置共享数据
    public final void close();//关闭通道
}
  
面试官:NIO非阻塞网络编程原理了解吗?一文深度讲解避坑

13、NIO网络编程应用实例-群聊系统

编写一个 NIO 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
2) 实现多人群聊
3) 服务器端:可以监测用户上线,离线,并实现消息转发功能
4) 客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发
得到)
5) 目的:进一步理解 NIO 非阻塞网络编程机制

服务端以及客户端

 public class GroupChatServer {
    //定义基本属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;
    /**
     * 构造器,初始化工作
     * **/
    public GroupChatServer(){
        try {
            //得到选择器
            selector = Selector.open();
            //得到ServerSocketChannel
            listenChannel= ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将这个channel注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //监听
    public void listen(){
        System.out.println("监听程序:"+Thread.currentThread().getName());
            try {
                while(true){
                int count = selector.select();
                    if (count > 0) {
                        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                        while(iterator.hasNext()){
                            SelectionKey key = iterator.next();
                            //监听到accept
                            if(key.isAcceptable()) {
                                SocketChannel sc = listenChannel.accept();
                                sc.configureBlocking(false);
                                //将该 sc 注册到seletor
                                sc.register(selector, SelectionKey.OP_READ);
                                //提示
                                System.out.println(sc.getRemoteAddress() + " 上线 ");
                            }
                            if(key.isReadable()) { //通道发送read事件,即通道是可读的状态
                                //处理读 (专门写方法..)
                                readData(key);
                            }
                            //当前的key 删除,防止重复处理
                            iterator.remove();
                        }
                    }else{
                        System.out.println("等待......");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    //读取客户端消息
    private void readData(SelectionKey key) {
        //取到关联的channle
        SocketChannel channel = null;
        try {
            //得到channel
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据count的值做处理
            if(count > 0) {
                //把缓存区的数据转成字符串
                String  msg  = new String(buffer.array());
                //输出该消息
                System.out.println("form 客户端: " + msg);
                //向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
                sendInfoToOtherClients(msg, channel);
            }
        }catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            }catch (IOException e2) {
                e2.printStackTrace();;
            }
        }
    }
    //转发消息给其它客户(通道)
    private void sendInfoToOtherClients(String msg, SocketChannel self ) throws  IOException{
        System.out.println("服务器转发消息中...");
        System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
        //遍历 所有注册到selector 上的 SocketChannel,并排除 self
        for(SelectionKey key: selector.keys()) {
            //通过 key  取出对应的 SocketChannel
            Channel targetChannel = key.channel();
            //排除自己
            if(targetChannel instanceof  SocketChannel && targetChannel != self) {
                //转型
                SocketChannel dest = (SocketChannel)targetChannel;
                //将msg 存储到buffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                //将buffer 的数据写入 通道
                dest.write(buffer);
            }
        }
    }
    public static void main(String[] args) {
        //创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
//可以写一个Handler
class MyHandler {
    public void readData() {
    }
    public void sendInfoToOtherClients(){
    }
}
  
 package com.courage.groupchat;
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.Scanner;
public class GroupChatClient {
    //定义相关的属性
    private final String HOST = "127.0.0.1"; // 服务器的ip
    private final int PORT = 6667; //服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
    //构造器, 完成初始化工作
    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok...");
    }
    //向服务器发送消息
    public void sendInfo(String info) {
        info = username + " 说:" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    //读取从服务器端回复的消息
    public void readInfo() {
        try {
            int readChannels = selector.select();
            if(readChannels > 0) {//有可以用的通道
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if(key.isReadable()) {
                        //得到相关的通道
                        SocketChannel sc = (SocketChannel) key.channel();
                        //得到一个Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的selectionKey, 防止重复操作
            } else {
                //System.out.println("没有可以用的通道...");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
        //启动我们客户端
        GroupChatClient chatClient = new GroupChatClient();
        //启动一个线程, 每个3秒,读取从服务器发送数据
        new Thread() {
            public void run() {
                while (true) {
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
  

文章来源:智云一二三科技

文章标题:面试官:NIO非阻塞网络编程原理了解吗?一文深度讲解避坑

文章地址:https://www.zhihuclub.com/185621.shtml

关于作者: 智云科技

热门文章

评论已关闭

6条评论

  1. There are numerous handicapping angles in horse racing, all of which can lead to profits when identified and applied at the right time

  2. The aromatase inhibitor letrozole induces ovulation in women with PCOS without having anti estrogenic effects on the endometrium

  3. No blood work, I reiterate, lesson learned Objectives Accumulating evidence describes the effects of oestrogen and other gonadal hormones on the central nervous system and, in particular, on the mental state of women

  4. A higher rate of early pregnancy loss in African American women compared to Caucasian women has been previously reported following IVF 36, 37

网站地图