Netty-1-IO模型

1.Netty是什么?

Netty是一个处理网络高并发的框架

  1. .Netty 是由 JBOSS 提供的一个 Java 开源框架,现为 Github上的独立项目。
    2). Netty 是一个异步的、基于事件驱动的网络应用框架,用以快速开发高性能、高可
    靠性的网络 IO 程序。
  2. .Netty主要针对在TCP协议下,面向Clients端的高并发应用,或者Peer-to-Peer场景下
    大量数据持续传输的应用。
  3. .Netty本质是一个NIO框架,适用于服务器通讯相关的多种应用场景
  4. .要透彻理解Netty , 需要先学习 NIO , 这样我们才能阅读 Netty 的源码。

TCP/IP ---> JDK ---> NIO ---> Netty

I/O模型

Java共支持3种网络编程模型/IO模式:BIO、NIO、AIO
BIO、NIO、AIO适用场景分析

  1. BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,
    并发局限于应用中,JDK1.4以前的唯一选择,但程序简单易理解。
    在这里插入图片描述

  2. NIO方式适用于连接数目多且连接比较短(netty基于NIO 但是支持长连接)的架构,比如聊天服务器,弹幕
    系统,服务器间通讯等。编程比较复杂,JDK1.4开始支持。
    在这里插入图片描述

  3. AIO方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分
    调用OS参与并发操作,编程比较复杂,JDK7开始支持,使用不是很广泛。

BIO编程简单流程

  1. 服务器端启动一个ServerSocket
  2. 客户端启动Socket对服务器进行通
    信,默认情况下服务器端需要对每
    个客户 建立一个线程与之通讯
  3. 客户端发出请求后, 先咨询服务器
    是否有线程响应,如果没有则会等
    待,或者被拒绝
  4. 如果有响应,客户端线程会等待请
    求结束后,在继续执行
package com.atguigu.bio;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 启动后 telnet 127.0.0.1 6666 
 *       send  msg 
 *       进行测试
 */
public class BIOServer {
    public static void main(String[] args) throws Exception {

        //线程池机制

        //思路
        //1. 创建一个线程池
        //2. 如果有客户端连接,就创建一个线程,与之通讯(单独写一个方法)

        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器启动了");

        while (true) {

            System.out.println("线程信息 id =" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());
            //监听,等待客户端连接
            System.out.println("等待连接....");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            //就创建一个线程,与之通讯(单独写一个方法)
            newCachedThreadPool.execute(new Runnable() {
                public void run() { //我们重写
                    //可以和客户端通讯
                    handler(socket);
                }
            });

        }


    }

    //编写一个handler方法,和客户端通讯
    public static void handler(Socket socket) {

        try {
            System.out.println("线程信息 id =" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //通过socket 获取输入流
            InputStream inputStream = socket.getInputStream();

            //循环的读取客户端发送的数据
            while (true) {

                System.out.println("线程信息 id =" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());

                System.out.println("read....");
               int read =  inputStream.read(bytes);
               if(read != -1) {
                   System.out.println(new String(bytes, 0, read
                   )); //输出客户端发送的数据
               } else {
                   break;
               }
            }


        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

Java BIO问题

  1. 每个请求都需要创建独立的线程,与对应的客户端进行数据
    Read,业务处理,数据 Write
  2. 当并发数较大时,需要创建大量线程来处理连接,系统资源占
    用较大
  3. 连接建立后,如果当前线程暂时没有数据可读,则线程就阻塞
    在 Read 操作上,造成线程资源浪费

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(通道|类似于BIO的Socket|)Buffer(缓冲区),
    Selector(选择器)

  4. NIO是面向缓冲区 ,或者面向块编程的。数据读取到一个
    它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就
    增加了处理过程中的灵活性,使用它可以提供非阻塞式的高
    伸缩性网络

在这里插入图片描述

程序即客户端(Client/Socket)会前往缓冲区(Buffer)读取数据 缓冲区和通道(Channel)之间是可以相互通讯的,选择器(Selector)会与通道进行交互,通道会去缓冲区取数据,客户端会将数据放入缓冲区,程序不再与通道进行交互,可以通过Buffer实现非阻塞

  1. Java NIO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得
    到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线
    程阻塞
    ,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。 非阻塞
    写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这
    个线程同时可以去做别的事情。
    线程去通道读取或发送数据时,选择器能感知到通道是否有数据发送或接收,一个选择器可关联多个通道,当某个通道没有数据时,选择器回去执行其他通道的任务,不会阻塞线程 (事件驱动)

  2. 通俗理解:NIO是可以做到用一个线程来处理多个操作的。假设有10000个请求过来,
    根据实际情况,可以分配50或者100个线程来处理。不像之前的阻塞IO那样,非得分
    配10000个(指一个线程处理一个操作)。

  3. HTTP2.0使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求
    的数量比HTTP1.1大了好几个数量级。

NIO 和 BIO 的比较

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

NIO - Buffer(缓冲区)

缓冲区(Buffer):缓冲区本质上是一个可以读写数据的内存块,可以理解成是一个
容器对象(含数组),该对象提供了一组方法,可以更轻松地使用内存块,,缓冲区对
象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况。Channel 提供从文件、
网络读取数据的渠道,但是读取或写入的数据都必须经由 Buffer
在这里插入图片描述
Buffer类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素

private int mark = -1;   
标记
private int position = 0; 
位置,下一个要被读或写的元素的索引,
每次读写缓冲区数据时都会改变改值,
为下次读写作准备
private int limit;
表示缓冲区的当前终点,不能对缓冲区
超过极限的位置进行读写操作。且极限
是可以修改的
private int capacity;
容量,即可以容纳的最大数据量;在缓
冲区创建时被设定并且不能改变

Selector 、 Channel 和 Buffer 的关系图(简单版)

关系图的说明:

  1. 每个channel 都会对应一个Buffer
  2. Selector 对应一个线程, 一个线程对应多个channel(连接)
  3. 该图反应了有三个channel 注册到 该selector //程序
  4. 程序切换到哪个channel 是有事件决定的, Event 就是一个重要的概念
  5. Selector 会根据不同的事件,在各个通道上切换
  6. Buffer 就是一个内存块 , 底层是有一个数组
  7. 数据的读取写入是通过Buffer, 这个和BIO , BIO 中要么是输入流,或者是
    输出流, 不能双向,但是NIO的Buffer 是可以读也可以写, 需要 flip 方法切换
  8. channel 是双向的, 可以返回底层操作系统的情况, 比如Linux , 底层的操作系统
    通道就是双向的.
    在这里插入图片描述

Buffer 案例

package com.atguigu.nio;

import java.nio.IntBuffer;

public class BasicBuffer {
    public static void main(String[] args) {

        //举例说明Buffer缓冲区 的使用 (简单说明)
        //创建一个Buffer, 大小为 5, 即可以存放5个int Buffer有其他类型
        IntBuffer intBuffer = IntBuffer.allocate(5);

        //向buffer 存放数据 capacity() 容量
        for(int i = 0; i < intBuffer.capacity(); i++) {
            intBuffer.put( i * 2);
        }
		

        //将Buffer转换 读写翻转 一定要切换
        intBuffer.flip();
        //1,2  从哪个下标开始读取,当前读取到哪个数据了
        intBuffer.position(3);
        System.out.println(intBuffer.get());
        //表示缓冲区的当前终点
        intBuffer.limit(4);
        //intBuffer.hasRemaining() 有剩余的就继续读
        while (intBuffer.hasRemaining()) {
            //intBuffer.get() Buffer维护了一个索引,每get一次就会取出一个索引
            System.out.println(intBuffer.get());
        }
    }
}

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();//告知此缓冲区是否为直接缓冲区
}

ByteBuffer

从前面可以看出对于 Java 中的基本数据类型(boolean除外),都有一个 Buffer 类型与之
相对应,最常用的自然是ByteBuffer 类(二进制数据),该类的主要方法如下:

public abstract class ByteBuffer {
//缓冲区创建相关api
public static ByteBuffer allocateDirect(int capacity)//创建直接缓冲区
public static ByteBuffer allocate(int capacity)//设置缓冲区的初始容量

public static ByteBuffer wrap(byte[] array)//把一个数组放到缓冲区中使用
//构造初始化位置offset和上界length的缓冲区
public static ByteBuffer wrap(byte[] array,int offset, int length)
//缓存区存取相关API
public abstract byte get( );//从当前位置position上get,get之后,position会自动+1
public abstract byte get (int index);//从绝对位置get
public abstract ByteBuffer put (byte b);//从当前位置上添加,put之后,position会自动+1
public abstract ByteBuffer put (int index, byte b);//从绝对位置上put

}

通道 Channel

基本介绍

  1. NIO的通道(Channel)类似于流,但有些区别如下:
    • 通道可以同时进行读写,而流只能读或者只能写
    • 通道可以实现异步读写数据
    • 通道可以从缓冲读数据,也可以写数据到缓冲:
    在这里插入图片描述
  2. BIO 中的 stream 是单向的,例如 FileInputStream 对
    象只能进行读取数据的操作,而 NIO 中的通道
    (Channel)是双向的,可以读操作,也可以写操作。
  3. Channel在NIO中是一个接口
    public interface Channel extends Closeable{}
  4. 常用的 Channel 类有:FileChannel、
    DatagramChannel、ServerSocketChannel 和
    SocketChannel。【ServerSocketChanne 类似
    ServerSocket , SocketChannel 类似 Socket

    在服务器端会有一个ServerSocketChannel,当一个客户端有个连接进来的时候先找主线程,主线程通过ServerSocketChannel,给每一个客户端创建一个对应的SocketChannel
  5. FileChannel 用于文件的数据读写,
    DatagramChannel 用于 UDP 的数据读写,
    ServerSocketChannel 和 SocketChannel 用于 TCP
    的数据读写。
  • 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),把数据从当
    前通道复制给目标通道
    在这里插入图片描述

FileChannel

案例 1 输出文件到本地

package com.atguigu.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel01 {
    public static void main(String[] args) throws Exception{

        String str = "hello";

        //创建一个输出流->channel
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");

        //通过 fileOutputStream 获取 对应的 FileChannel  FileChannel 会对文件IO流进行包装
        //这个 fileChannel 真实 类型是  FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

        //创建一个缓冲区 ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        //将 str 放入 byteBuffer
        byteBuffer.put(str.getBytes());


        //对byteBuffer 进行flip
        byteBuffer.flip();

        //将byteBuffer 缓冲区数据写入到 fileChannel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();

    }
}

案例 2 从本地读取文件

package com.atguigu.nio;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel02 {
    public static void main(String[] args) throws Exception {

        //创建文件的输入流
        File file = new File("d:\\file01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);

        //通过fileInputStream 获取对应的FileChannel -> 实际类型  FileChannelImpl
        FileChannel fileChannel = fileInputStream.getChannel();

        //创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        //将 通道的数据读入到Buffer
        fileChannel.read(byteBuffer);

        //将byteBuffer 的 字节数据 转成String
        System.out.println(new String(byteBuffer.array()));
        fileInputStream.close();

    }
}

在这里插入图片描述
案例3 使用一个Buffer完成文件的读取

package com.atguigu.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {

        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) { //循环读取

            //这里有一个重要的操作,一定不要忘了
            /*
             public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
             */
            byteBuffer.clear(); //清空buffer
            int read = fileChannel01.read(byteBuffer);
            System.out.println("read =" + read);
            if(read == -1) { //表示读完
                break;
            }
            //将buffer 中的数据写入到 fileChannel02 -- 2.txt
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }

        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}

案例 4 transferFrom 方法拷贝文件
public long transferFrom(ReadableByteChannel src, long position, long count),从目标通道
中复制数据到当前通道
public long transferTo(long position, long count, WritableByteChannel target),把数据从当
前通道复制给目标通道

package com.atguigu.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class NIOFileChannel04 {
    public static void main(String[] args)  throws Exception {

        //创建相关流
        FileInputStream fileInputStream = new FileInputStream("d:\\a.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\a2.jpg");

        //获取各个流对应的filechannel
        FileChannel sourceCh = fileInputStream.getChannel();
        FileChannel destCh = fileOutputStream.getChannel();

        //使用transferForm完成拷贝
        destCh.transferFrom(sourceCh,0,sourceCh.size());
        //关闭相关通道和流
        sourceCh.close();
        destCh.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}

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

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

package com.atguigu.nio;

import java.nio.ByteBuffer;

public class NIOByteBufferPutGet {
    public static void main(String[] args) {

        //创建一个Buffer
        ByteBuffer buffer = ByteBuffer.allocate(64);

        //类型化方式放入数据
        buffer.putInt(100);
        buffer.putLong(9);
        buffer.putChar('尚');
        buffer.putShort((short) 4);

        //取出
        buffer.flip();

        System.out.println();
        //此处不安指定类型顺序取数据会报错
        System.out.println(buffer.getInt());
        System.out.println(buffer.getLong());
        System.out.println(buffer.getChar());
        System.out.println(buffer.getShort());
        

    }
}

2) 可以将一个普通Buffer 转成只读Buffer

package com.atguigu.nio;

import java.nio.ByteBuffer;

public class ReadOnlyBuffer {
    public static void main(String[] args) {

        //创建一个buffer
        ByteBuffer buffer = ByteBuffer.allocate(64);

        for(int i = 0; i < 64; i++) {
            buffer.put((byte)i);
        }
        //读取
        buffer.flip();

        //得到一个只读的Buffer
        ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
        System.out.println(readOnlyBuffer.getClass());

        //读取
        while (readOnlyBuffer.hasRemaining()) {
            System.out.println(readOnlyBuffer.get());
        }

        readOnlyBuffer.put((byte)100); //ReadOnlyBufferException
    }
}

3) NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进
行修改, 而如何同步到文件由NIO 来完成.
MappedByteBuffer 可让文件直接在内存(堆外内存)修改, 操作系统不需要拷贝一次

package com.atguigu.nio;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/*
说明
1. MappedByteBuffer 可让文件直接在内存(堆外内存)修改, 操作系统不需要拷贝一次
 */
public class MappedByteBufferTest {
    public static void main(String[] args) throws Exception {

        RandomAccessFile randomAccessFile = new RandomAccessFile("1.txt", "rw");
        //获取对应的通道
        FileChannel channel = randomAccessFile.getChannel();

        /**
         * 参数1: FileChannel.MapMode.READ_WRITE 使用的读写模式
         * 参数2: 0 : 可以直接修改的起始位置
         * 参数3:  5: 是映射到内存的大小(不是索引位置) ,即将 1.txt 的多少个字节映射到内存
         * 可以直接修改的范围就是 0-5
         * 实际类型 DirectByteBuffer
         */
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);

        mappedByteBuffer.put(0, (byte) 'H');
        mappedByteBuffer.put(3, (byte) '9');
        mappedByteBuffer.put(5, (byte) 'Y');//IndexOutOfBoundsException

        randomAccessFile.close();
        System.out.println("修改成功~~");



    }
}

  1. 前面我们讲的读写操作,都是通过一个Buffer 完成的,NIO 还支持 通过多个
    Buffer (即 Buffer 数组) 完成读写操作,即 Scattering 和 Gathering
package com.atguigu.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Scattering:将数据写入到buffer时,可以采用buffer数组,依次写入  [分散]
 * Gathering: 从buffer读取数据时,可以采用buffer数组,依次读
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws Exception {

        //使用 ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //绑定端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定端口到socket ,并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等客户端连接(telnet)
        SocketChannel socketChannel = serverSocketChannel.accept();
        //假定从客户端接收8个字节
        int messageLength = 8;
        //循环的读取
        while (true) {

            int byteRead = 0;

            while (byteRead < messageLength ) {
                long l = socketChannel.read(byteBuffers);
                //累计读取的字节数
                byteRead += l;
                System.out.println("byteRead=" + byteRead);
                //使用流打印, 看看当前的这个buffer的position 和 limit
                Arrays.asList(byteBuffers).stream().map(b ->{
                    return  "postion=" + b.position() + ", limit=" + b.limit();
                }).forEach(System.out::println);
            }

            //将所有的buffer进行flip
            Arrays.asList(byteBuffers).forEach(buffer -> {
                buffer.flip();
            });

            //将数据读出显示到客户端
            long byteWirte = 0;
            while (byteWirte < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWirte += l;
            }

            //将所有的buffer 进行clear
            Arrays.asList(byteBuffers).forEach(buffer-> {
                buffer.clear();
            });

            System.out.println("byteRead:=" + byteRead + " byteWrite=" + byteWirte + ", messagelength" + messageLength);
        }




    }
}

Selector 选择器

基本介绍

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

  2. Selector 能够检测多个注册的通道上是否有事件发生(注意:多个Channel以
    事件的方式可以注册到同一个Selector)
    ,如果有事件发生,便获取事件然
    后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个
    通道,也就是管理多个连接和请求。

  3. 只有在 连接/通道 真正有读写事件发生时,才会进行读写,就大大地减少
    了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程

  4. 避免了多线程之间的上下文切换导致的开销

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

Selector类相关方法
Selector 类是一个抽象类, 常用方法和说明如下:

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

一个线程对应一个Selector 复用器,当线程连接到Selector时,Selector会调用select方法并返回这个复用器对应的Selectionkey集合,可以通过这个key,看来具体是哪个事件,而后根据事件做对应操作 ,通过key取到对应通道(Channel)再操作
select方法 带参数是阻塞的方法,如果关联的通道都没有事件,那会阻塞在这里

注意事项
一. NIO中的 ServerSocketChannel功能类似ServerSocketSocketChannel功能类
Socket
二. selector 相关方法说明

  1. selector.select()//阻塞 监控所有注册的通道,当其中有 IO 操作可以进行时,将对应的 SelectionKey 加入到内部集合中并返回,参数用来设置超时时间
  2. selector.select(1000);//阻塞1000毫秒,在1000毫秒后返回
  3. selector.wakeup();//唤醒selector
  4. selector.selectNow();//不阻塞,立马返还

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

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

在这里插入图片描述

  1. 当客户端连接时,会通过ServerSocketChannel 得到 SocketChannel

  2. 将socketChannel注册到Selector上,register(Selector sel, int ops), 一个selector上可以注册多个SocketChannel

  3. 注册后返回一个 SelectionKey, 会和该Selector 关联(集合)

  4. Selector 进行监听 select 方法, 返回有事件发生的通道的个数.

  5. 进一步得到各个 SelectionKey (有事件发生)

  6. 在通过 SelectionKey 反向获取SocketChannel , 方法 channel()

  7. 可以通过 得到的 channel , 完成业务处理

SelectionKey

  1. 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;

ServerSocketChannel

  1. ServerSocketChannel 在服务器端监听新的客户端 Socket 连接
  2. 相关方法如下
    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),注册一个选择器并设置
    监听事件
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值