Netty核心技术三--NIO编程

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

  5. Java NIO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情。

    image-20230514104357723

  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(选择器
  4. )用于监听多个通道的事件(比如:连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道

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

一张图描述NIO 的 Selector 、 Channel 和 Buffer 的关系((简单版)

image-20230514105551263

关系图说明:

  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 , 底层的操作系统通道就是双向的.

3.1 缓冲区(Buffer)

image-20230514110034489

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

3.1.1 Buffer 类及其子类

3.1.1.1 Buffer继承关系

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

记忆方法:java8大基本类型除了bool类型其他都有buffer对应的子类

  1. ByteBuffer,存储字节数据到缓冲区
  2. ShortBuffer,存储字符串数据到缓冲区
  3. CharBuffer,存储字符数据到缓冲区
  4. IntBuffer,存储整数数据到缓冲区
  5. LongBuffer,存储长整型数据到缓冲区
  6. DoubleBuffer,存储小数到缓冲区
  7. FloatBuffer,存储小数到缓冲区

image-20230514110227470

3.1.1.2 Buffer的四个核心属性

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

image-20230514111627061

  • Capacity:容量,即可以容纳的最大数据量;在缓冲区创建时被设定并且不能改变
  • Limit:表示缓冲区的当前终点,不能对缓冲区超过极限的位置进行读写操作。且极限是可以修改的
  • Position: 位置,下一个要被读或写的元素的索引每次读写缓冲区数据时都会改变改值,为下次读写作准备
  • Mark: 标记
3.1.1.3 Buffer类相关方法

image-20230514112806559

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();//告知此缓冲区是否为直接缓冲区
}
3.1.1.4 ByteBuffer(其他子类类似只不过类型不同)

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

image-20230514113128206

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
}

3.2 通道(Channel)

3.2.1 基本介绍

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

    • 通道可以同时进行读写,而流只能读或者只能写

    • 通道可以实现异步读写数据

    • 通道可以从缓冲读数据,也可以写数据到缓冲

      image-20230514113526333

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

  3. Channel在NIO中是一个接口

    public interface Channel extends Closeable{
          
          }
    
  4. 常用的 Channel 类有:FileChannelDatagramChannelServerSocketChannelSocketChannel。【ServerSocketChanne 类似 ServerSocket , SocketChannel 类似 Socket】

    image-20230514114217766

    • FileChannel 用于文件的数据读写
    • DatagramChannel 用于 UDP 的数据读写
    • ServerSocketChannel 和 SocketChannel 用于 TCP 的数据读写

3.2.2 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),把数据从当前通道复制给目标通道

3.2.3 应用实例1-本地文件写数据

实例要求:

  1. 使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道),将"hello,尚硅谷"写入到file01.txt 中
  2. 文件不存在就创建

image-20230514120018786

package site.zhourui.nioAndNetty.nio;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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://FileChannel01.txt");

        //通过 fileOutputStream 获取 对应的 FileChannel
        //这个 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();

    }
}

执行结果:

image-20230514115903121

3.2.4 应用实例2-本地文件读数据

image-20230514120136539

实例要求:

  1. 使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道),将file01.txt 中的数据读入到程序,并显示在控制台屏幕
  2. 假定文件已经存在
package site.zhourui.nioAndNetty.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://FileChannel01.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();

    }
}

执行结果:

image-20230514120952125

3.2.5 应用实例3-使用一个Buffer完成文件读取

image-20230514122635239

实例要求:

  1. 使用 FileChannel(通道) 和 方法 read , write,完成文件的拷贝
  2. 拷贝一个文本文件 1.txt , 放在项目下即可
package site.zhourui.nioAndNetty.nio;

import java.io.File;
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{
    
    
        File file = new File("d://FileChannel01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream(new File("d://copy.txt"));
        FileChannel channel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(5);
        while (true){
    
     //循环读取
            //这里有一个重要的操作,一定不要忘了
            /*
             public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
             */
            byteBuffer.clear(); //清空buffer
            int read = fileChannel.read(byteBuffer);
            if (read==-1){
    
    //表示读完
                break;
            }
            //将buffer 中的数据写入到  -- copy.txt
            byteBuffer.flip();
            channel.write(byteBuffer);
        }
        //关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}

执行结果:

image-20230514122428067

注意事项:

  • 在每次循环读取数据到byteBuffer之前一定要清空buffer,即byteBuffer.clear();

    //clear方法
    public final Buffer clear() {
           
           
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }			
    
  • 如果不进行清空buffer,那么5和limit就会一直相等导致read变量后续一直为0,不能跳出循环

    image-20230514123505470

    image-20230514123700322

3.2.6 应用实例4-拷贝文件transferFrom 方法

实例要求:

  1. 使用 FileChannel(通道) 和 方法 transferFrom ,完成文件的拷贝
  2. 拷贝一张图片
package site.zhourui.nioAndNetty.nio;

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

public class NIOFileChannel04 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //创建相关流
        FileInputStream fileInputStream = new FileInputStream("D:\\1.jpeg");
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\2.jpeg");

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

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

也可以使用transferTo

sourceCh.transferTo(0,sourceCh.size(),destCh);

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

3.3.1 ByteBuffer 支持类型化的put 和 get

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

image-20230514142757848

3.3.2 只读Buffer-asReadOnlyBuffer

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

image-20230514143108186

3.3.3 映射Buffer-MappedByteBuffer

NIO 还提供了 MappedByteBuffer, 可以让文件直接在内存(堆外的内存)中进行修改, 而如何同步到文件由NIO 来完成.

  • MappedByteBuffer 可让文件直接在内存(堆外内存)修改, 操作系统不需要拷贝一次

文件之前内容:

image-20230520102711717

package site.zhourui.nioAndNetty.nio;

import java.io.IOException;
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 IOException {
    
    
        // 创建一个随机访问文件流以从具有指定名称的文件中读取,并可选择写入。
        RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\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(4, (byte) 'Y');

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

    }
}

执行结果:

image-20230520102852850

注意:

channel.map第三个参数为5时mappedByteBuffer.put(5, (byte) ‘Y’);会爆IndexOutOfBoundsException

即 5: 是映射到内存的大小(不是索引位置)

3.3.4 Buffer的分散Scattering和聚集Gathering

前面我们讲的读写操作,都是通过一个Buffer 完成的,NIO还支持通过多个Buffer (即 Buffer 数组) 完成读写操作,即 ScatteringGathering

package site.zhourui.nioAndNetty.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();
        int messageLength = 8;   //假定从客户端接收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(buffer -> "postion=" + buffer.position() + ", limit=" + buffer.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);
        }




    }
}
3.3.4.1 使用telnet测试
#连接服务端
telnet 127.0.0.1 7000
#发送4字节数据
send hellp

执行结果:

  • Scattering:将数据写入到buffer时,可以采用buffer数组,依次写入 [分散]
  • Gathering: 从buffer读取数据时,可以采用buffer数组,依次

image-20230520111826591

3.4 Selector(选择器)

3.4.1 基本介绍

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

3.4.2 Selector示意图和特点说明

image-20230520112905037

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

3.4.3 Selector类相关方法

image-20230520113353452

Selector 类是一个抽象类:

public abstract class Selector implements Closeable 

常用方法和说明如下:

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

注意事项

  1. ) NIO中的 ServerSocketChannel功能类似ServerSocket,SocketChannel功能类似Socket
  2. selector 相关方法说明
    • selector.select()//阻塞
    • selector.select(1000);//阻塞1000毫秒,在1000毫秒后返回
    • selector.wakeup();//唤醒selector
      • 将阻塞select中的selector唤醒
    • selector.selectNow();//不阻塞,立马返还

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

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

image-20230520113646143

  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 , 完成业务处理
3.4.4.1 应用实例5-实现服务器端和客户端之间的数据简单通讯(非阻塞)

案例要求:

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

服务端注意事项:

  1. serverSocketChannel拿到后一定要设置为非阻塞configureBlocking(false)

  2. 客户端连接服务器时创建socketChannel之后一定要设置为非阻塞

    否则会爆如下异常IllegalBlockingModeException:

    image-20230520122300334

  3. register第三个参数可以关联buffer

  4. 我们可以通过key.channel()拿到对应的channel

  5. 我们可以通过key.attachment()拿到对应的buffer

  6. SelectionKey事件

    • OP_READ–读事件
    • OP_WRITE–写事件
    • OP_CONNECT–客户端连接事件
    • OP_ACCEPT–数据接收事件
  7. 处理过对应事件的key一定要从selectedKeys中移除,防止重复操作

     keyIterator.remove();
    
  8. accept方法是阻塞的,为什么我们serverSocketChannel.accept()程序仍然是非阻塞的?

    • 因为NIO服务端是isAcceptable为true才去accept的,肯定就可以accept成功
    • 而BIO则不知道数据什么时候到达accept就会一直阻塞
package site.zhourui.nioAndNetty.nio.nioPractise;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

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

        //创建ServerSocketChannel -> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //绑定一个端口6666, 在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(8888));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        //得到一个Selecor对象
        Selector selector = Selector.open();

        //把 serverSocketChannel 注册到  selector 关心 事件为 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1

        //循环等待客户端连接
        while (true) {
    
    
            //这里我们等待1秒,如果没有事件发生, 返回
            if (selector.select(1000)==0){
    
    
                System.out.println("服务器等待了1秒,无连接");
                continue;
            }
            //如果返回的>0, 就获取到相关的 selectionKey集合
            //1.如果返回的>0, 表示已经获取到关注的事件
            //2. selector.selectedKeys() 返回关注事件的集合
            //   通过 selectionKeys 反向获取通道
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            System.out.println("selectionKeys 数量 = " + selectionKeys.size());
            //遍历 Set<SelectionKey>, 使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

            //监听事件
            while (keyIterator.hasNext()){
    
    
                //获取到SelectionKey
                SelectionKey key = keyIterator.next();
                //根据key 对应的通道发生的事件做相应处理
                if(key.isAcceptable()){
    
    //如果是 OP_ACCEPT, 有新的客户端连接
                    //该该客户端生成一个 SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode());
                    //将  SocketChannel 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel
                    //关联一个Buffer
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                    System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4..

                }
                if (key.isReadable()){
    
    //发生 OP_READ
                    //通过key 反向获取到对应channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("form 客户端 " + new String(buffer.array()));
                }

                //手动从集合中移动当前的selectionKey, 防止重复操作
                keyIterator.remove();
            }
        }


    }
}
3.4.4.1.2 NIOClient
  1. 客户端的socketChannel也一定要设置为非阻塞
  2. ByteBuffer.wrap(byte[] array)方法将字节数组包裹到缓冲区中。可以获取一个刚好array大小的buffer
package site.zhourui.nioAndNetty.nio.nioPractise;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
    
    
    public static void main(String[] args) throws Exception{
    
    
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //提供服务器端的ip 和 端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8888);
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)){
    
    
            while (!socketChannel.finishConnect()){
    
    
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其它工作..");
            }
        }
        //...如果连接成功,就发送数据
        String str = "hello~";
        //Wraps a byte array into a buffer
        //将字节数组包装到缓冲区中。
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据,将 buffer 数据写入 channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
3.4.4.1.3 开启服务端连接一个客户端

image-20230520143054223

3.4.4.1.4 开启服务端连接两个客户端

image-20230520143359245

4. 应用实例六-群聊系统

实例要求:

  1. 编写一个 NIO 群聊系统,实现服务器 端和客户端之间的数据简单通讯(非 阻塞)

  2. 实现多人群聊

  3. 服务器端:可以监测用户上线,离线, 并实现消息转发功能

  4. 客户端:通过channel 可以无阻塞发送 消息给其它所有用户,同时可以接受 其它用户发送的消息(有服务器转发得 到)

  5. 目的:进一步理解NIO非阻塞网络编程 机制

  6. 服务端效果:

    image-20230527144818183

  7. 客户端效果:

    image-20230527144843872

4.1 服务端

代码说明:

  1. 服务端通过构造器对selector,ServerSocketChannel进行初始化,并将ServerSocketChannel设置非阻塞模式,然后将(接收事件OP_ACCEPT)注册到selector

  2. listen()监听方法

    1. 自旋的方式判断selector中是否有发生事件的channel的key

    2. 如果有就遍历发生事件的key->selectedKeys

      1. 如果是accept事件代表有客户端接入,为客户端创建SocketChannel并注册到selector中监听(读事件OP_READ)

      2. 如果是Readable事件代表客户端发送了消息,我们需要处理读,通过readData(key)方法来实现

      3. 每次处理完key需要将当前的key 删除,防止重复处理

        • iterator.remove();
          
    3. 如果没有服务器就等待或者做其他事

  3. readData(key)读取客户端消息

    1. 通过key获取到对应的通道
    2. 然后通过buffer读取通道中的数据
      1. 如果没有IOException代表读到数据
        1. 向其它的客户端转发消息(去掉自己), 专门写一个方法来处理sendInfoToOtherClients(msg, channel)
      2. 如果发生IOException代表该客户端已离线
        1. 取消注册
        2. 关闭通道
  4. sendInfoToOtherClients(msg, channel)//转发消息给其它客户(通道)

    1. 拿到selector的所有keys
    2. 通过这些key可以拿到对应的channel,然后排除自己这个通道
    3. 向这些通道发送消息
package site.zhourui.nioAndNetty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class GroupChatServer {
    
    
    //定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    public static final int PORT = 8888;

    //构造器
    //初始化工作
    public GroupChatServer() {
    
    
        try {
    
    
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该listenChannel 注册到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
                        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() + " 上线 ");
                        } else if (key.isReadable()) {
    
    //通道发送read事件,即通道是可读的状态
                            //处理读 (专门写方法..)
                            readData(key);
                        }
                        //当前的key 删除,防止重复处理
                        iterator.remove();
                    }
                } else {
    
    
                    System.out.println("服务器等待....");
                }

            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            //发生异常处理....
        }

    }
    //读取客户端消息
    private void readData(SelectionKey key) {
    
    
        //得到channel
        SocketChannel channel = (SocketChannel) key.channel();
        //创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        try {
    
    
            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) {
    
    
//            e.printStackTrace();
            try {
    
    
                System.out.println(channel.getRemoteAddress() + " 离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ex) {
    
    
                ex.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());
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
    
    
        //创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}

4.2 客户端

代码说明:

  1. 客户端也通过构造器对selector,SocketChannel进行初始化,并将SocketChannel设置非阻塞模式,然后将(读事件OP_READ)注册到selector
  2. 通过Scanner键盘输入消息,然后通过sendInfo方法发送消息
  3. 启动一个线程, 每个3秒,读取从服务器发送数据readInfo
  4. sendInfo(info)
    1. 通过channel的write方法发送消息
  5. readInfo()
    1. 理论上这里需要判断事件类型的,但是客户端只会收到读事件
    2. 所以就只监听读事件读取,当读事件发生时代表服务器端向该客户端发送了消息,客户端读取消息即可
    3. 最后不要忘了iterator.remove()
package site.zhourui.nioAndNetty.nio.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.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {
    
    
    //定义相关的属性
    private final String HOST ="127.0.0.1";
    private final int PORT = 8888; //服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    //构造器, 完成初始化工作
    public GroupChatClient() throws IOException {
    
    
        selector=Selector.open();
        //连接服务器
        socketChannel= SocketChannel.open(new InetSocketAddress(HOST,PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        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();
                    //得到相关的通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    //得到一个Buffer
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    //读取
                    channel.read(buffer);
                    //把读到的缓冲区的数据转成字符串
                    String s = new String(buffer.array());
                    System.out.println(s);

                iterator.remove();//删除当前的selectionKey, 防止重复操作
                }
            }else {
    
    
                //System.out.println("没有可以用的通道...");
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
    
    
        GroupChatClient groupChatClient = new GroupChatClient();

        //启动一个线程, 每个3秒,读取从服务器发送数据
        new Thread(()->{
    
    
            while (true){
    
    
                groupChatClient.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();
            groupChatClient.sendInfo(s);
        }
    }
}

4.3 开启一个服务端三个客户端

image-20230527160203903

image-20230527160218671

image-20230527160230965

image-20230527160243601

GroupChatClient发送消息

image-20230527160448682

image-20230527160434889

image-20230527160501569

image-20230527160510976

5. NIO与零拷贝

5.1 零拷贝基本介绍

  1. 零拷贝是网络编程的关键,很多性能优化都离不开。
  2. 在 Java 程序中,常用的零拷贝有 mmap(内存映射)sendFile。那么,他们在OS 里,到底是怎么样的一个的设计?我们分析mmap 和sendFile这两个零拷贝
  3. 另外我们看下NIO 中如何使用零拷贝

5.2 传统IO数据读写

Java 传统 IO 和 网络编程的一段代码

image-20230527163814264

5.3 传统IO模型

DMA direct memory access:直接内存拷贝不使用CPU

image-20230527164549024

  1. 第一步先将数据进行DMA copy从硬件拷贝到内核buffer
  2. 第二步将数据通过CPU拷贝拷贝到用户buffer
  3. 第三步将数据通过CPU拷贝拷贝到网络层socket buffer
  4. 第四部将数据通过DMA copy从socket buffer拷贝到协议栈protocol engine

在不计首尾状态的转换的情况下

进行了4次拷贝,3次状态的切换

5.4 mmap 优化

mmap 通过内存映射,==将文件映射到内核缓冲区,同时,用户空间可以共享内核空间的数据。==这样,在进行网络传输时,就可以减少内核空间到用户控件的拷贝次数。如下图

image-20230527165537954

在不计首尾状态的转换的情况下

进行了3次拷贝,3次状态的切换

5.5 sendFile

Linux 2.1 版本 提供了 sendFile 函数,其基本 原理如下:数据根本不 经过用户态,直接从内 核缓冲区进入到 Socket Buffer,同时,由于和用 户态完全无关,就减少 了一次上下文切换

零拷贝从操作系统角 度,是没有cpu 拷贝

image-20230527165642937

在不计首尾状态的转换的情况下

进行了3次拷贝,3次状态的切换

5.6 sendFile 优化

  • Linux 在 2.4 版本中,做了 一些修改,避免了从内核 缓冲区拷贝到 Socket buffer 的操作,直接拷贝到 协议栈,从而再一次减少 了数据拷贝。具体如下图 和小结:

  • 这里其实有 一次cpu 拷贝 kernel buffer -> socket buffer 但是,拷贝的信息很少,比如 lenght , offset , 消耗低,可以 忽略

image-20230527165926779

5.7 零拷贝的再次理解

  • 我们说零拷贝,是从操作系统的角度来说的。因为内核缓冲区之间,没有数据是重复的(只有 kernel buffer 有一份数据)。
  • 零拷贝不仅仅带来更少的数据复制,还能带来其他的性能优势,例如更少的上下文切换,更少的 CPU 缓存伪共享以及无 CPU 校验和计算。

5.8 mmap 和 sendFile 的区别

  1. mmap 适合小数据量读写,sendFile 适合大文件传输。
  2. mmap 需要 4 次上下文切换,3 次数据拷贝;sendFile 需要3 次上下文切换,最少 2 次数据拷贝。
  3. sendFile 可以利用 DMA 方式,减少 CPU 拷贝,mmap 则不能(必须从内核拷贝到 Socket 缓冲区)。

5.9 NIO 零拷贝案例

案例要求:

  1. 使用传统的IO 方法传递一个大文件
  2. 使用NIO 零拷贝方式传递(transferTo)一个大文件
  3. 看看两种传递方式耗时时间分别是多少

5.9.1 传统的IO 方法传递一个大文件

5.9.1.1 OldIOServer
package site.zhourui.nioAndNetty.nio.zerocopy;

import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class OldIOServer {
    
    
    public static void main(String[] args) throws Exception {
    
    
        ServerSocket serverSocket = new ServerSocket(7001);

        while (true) {
    
    
            Socket socket = serverSocket.accept();
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());

            try {
    
    
                byte[] byteArray = new byte[4096];

                while (true) {
    
    
                    int readCount = dataInputStream.read(byteArray, 0, byteArray.length);

                    if (-1 == readCount) {
    
    
                        break;
                    }
                }
            } catch (Exception ex) {
    
    
                ex.printStackTrace();
            }
        }
    }
}
5.9.1.2 OldIOClient
package site.zhourui.nioAndNetty.nio.zerocopy;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.Socket;

public class OldIOClient {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Socket socket = new Socket("localhost", 7001);

        String fileName = "protoc-3.6.1-win32.zip";
        InputStream inputStream = new FileInputStream(fileName);

        DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());

        byte[] buffer = new byte[4096];
        long readCount;
        long total = 0;

        long startTime = System.currentTimeMillis();

        while ((readCount = inputStream.read(buffer)) >= 0) {
    
    
            total += readCount;
            dataOutputStream.write(buffer);
        }

        System.out.println("OldIOClient发送总字节数: " + total + ", 耗时: " + (System.currentTimeMillis() - startTime));

        dataOutputStream.close();
        socket.close();
        inputStream.close();
    }
}

执行结果:

image-20230527171706979

5.9.2 NIO零拷贝大文件

5.9.2.1 NewIOServer
package site.zhourui.nioAndNetty.nio.zerocopy;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

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

        InetSocketAddress address = new InetSocketAddress(7001);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        ServerSocket serverSocket = serverSocketChannel.socket();

        serverSocket.bind(address);

        //创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(4096);

        while (true) {
    
    
            SocketChannel socketChannel = serverSocketChannel.accept();

            int readcount = 0;
            while (-1 != readcount) {
    
    
                try {
    
    

                    readcount = socketChannel.read(byteBuffer);

                }catch (Exception ex) {
    
    
                    // ex.printStackTrace();
                    break;
                }
                //
                byteBuffer.rewind(); //倒带 position = 0 mark 作废
            }
        }
    }
}
5.9.2.2 NewIOClient
package site.zhourui.nioAndNetty.nio.zerocopy;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

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

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7001));
        String filename = "protoc-3.6.1-win32.zip";

        //得到一个文件channel
        FileChannel fileChannel = new FileInputStream(filename).getChannel();

        //准备发送
        long startTime = System.currentTimeMillis();

        //在linux下一个transferTo 方法就可以完成传输
        //在windows 下 一次调用 transferTo 只能发送8m , 就需要分段传输文件, 而且要主要
        //传输时的位置 =》 课后思考...
        //transferTo 底层使用到零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

        System.out.println("NewIOClient发送的总的字节数 =" + transferCount + " 耗时:" + (System.currentTimeMillis() - startTime));

        //关闭
        fileChannel.close();

    }
}

image-20230527171741771

案例总结:

  • 通过传统IO和零拷贝IO对相同文件拷贝用时对比,零拷贝效率更高
  • 在linux下一个transferTo 方法就可以完成传输
  • 在windows 下 一次调用 transferTo 只能发送8m , 就需要分段传输文件, 而且要主要

6. Java AIO 基本介绍

  1. JDK 7 引入了 Asynchronous I/O,即 AIO。在进行I/O编程中,常用到两种模式:ReactorProactor。Java 的 NIO 就是 Reactor,当有事件触发时,服务器端得到通知,进行相应的处理
  2. AIO 即 NIO2.0,叫做异步不阻塞的 IO。AIO 引入异步通道的概念,采用了Proactor 模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时间较长的应用
  3. 目前 AIO 还没有广泛应用,Netty 也是基于NIO, 而不是AIO,因此我们就不详解AIO了,有兴趣的同学可以参考 <> http://www.52im.net/thread-306-1-1.html

7. BIO、NIO、AIO对比表

image-20230527172255117

猜你喜欢

转载自blog.csdn.net/qq_31745863/article/details/130781372