首页 > 编程语言 >java之NIO简介

java之NIO简介

时间:2023-04-04 18:24:34浏览次数:47  
标签:java NIO 简介 System println ByteBuffer 缓冲区 通道 out

一、NIO基本简介

NIO (New lO)也有人称之为java non-blocking lO是从Java 1.4版本开始引入的一个新的IO API,可以替代标准的Java lO API。NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NIO支持面向缓冲区的、基于通道的IO操作。NIO将以更加高效的方式进行文件的读写操作。NIO可以理解为非阻塞IO,传统的IO的read和write只能阻塞执行,线程在读写IO期间不能干其他事情,比如调用socket.read()时,如果服务器一直没有数据传输过来,线程就一直阻塞,而NIO中可以配置socket为非阻塞模式。

  • NIO相关类都被放在java.nio包及子包下,并且对原java.io包中的很多类进行改写。
  • NIO有三大核心部分:Channel(通道),Buffer(缓冲区), Selector(选择器)
  • Java NlO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情。
  • 通俗理解:NIO是可以做到用一个线程来处理多个操作的。假设有1000个请求过来,根据实际情况,可以分配20或者80个线程来处理。不像之前的阻塞IO那样,非得分配1000个。

二、NIO 与 BIO的比较

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

NIO可以先将数据写入到缓冲区,然后再有缓冲区写入通道,因此可以做到同步非阻塞。

BIO则是面向的流,读写数据都是单向的。因此是同步阻塞。

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

NIO有三大核心部分: Channel(通道),Buffer(缓冲区),Selector(选择器)

Buffer(缓冲区)

        缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。相比较直接对数组的操作,Buffer APl更加容易操作和管理。

Channel(通道)

        Java NIO的通道类似流,但又有些不同:既可以从通道中读取数据,又可以写数据到通道。但流的(input或output)读写通常是单向的。通道可以非阻塞读取和写入通道,通道可以支持读取或写入缓冲区,也支持异步地读写。

Selector(选择器)

        Selector是一个ava NIO组件,可以能够检查一个或多个NIO通道,并确定哪些通道已经准备好进行读取或写入。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接,提高效率

在这里插入图片描述

  • 每个channel都会对应一个 Buffer
  • 一个线程对应Selector ,一个Selector对应多个channel(连接)程序
  • 切换到哪个channel是由事件决定的
  • Selector 会根据不同的事件,在各个通道上切换
  • Buffer 就是一个内存块,底层是一个数组
  • 数据的读取写入是通过 Buffer完成的,BlO中要么是输入流,或者是输出流,不能双向,但是NIO的Buffer是可以读也可以写。
  • Java NIO系统的核心在于:通道(Channel)和缓冲区(Buffer)。通道表示打开到lO设备(例如:文件、套接字)的连接。若需要使用NIO系统,需要获取用于连接IO设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。简而言之,Channel负责传输,Buffer负责存取数据

四、NIO核心一:缓存区 (Buffer)

缓冲区(Buffer)一个用于特定基本数据类型的容器。由 java.nio 包定义的,所有缓冲区 都是 Buffer 抽象类的子类.。Java NIO 中的 Buffer 主要用于与 NIO 通道进行 交互,数据是从通道读入缓冲区,从缓冲区写入通道中的

Buffer 类及其子类:

Buffer就像一个数组,可以保存多个相同类型的数据。根据 数据类型不同 ,有以下 Buffer 常用子类:  

  • ByteBuffer 
  • CharBuffer 
  • ShortBuffer 
  • IntBuffer 
  • LongBuffer 
  • FloatBuffer 
  • DoubleBuffer 

上述 Buffer 类他们都采用相似的方法进行管理数据,只是各自 管理的数据类型不同而已。都是通过如下方法获取一个 Buffer 对象:

static XxxBuffer allocate(int capacity) : 创建一个容量为capacity 的 XxxBuffer 对象
 

缓冲区的基本属性 Buffer 中的重要概念:

容量 (capacity) :作为一个内存块,Buffer具有一定的固定大小, 也称为"容量",缓冲区容量不能为负,并且创建后不能更改。

限制 (limit):表示缓冲区中可以操作数据的大小 (limit 后数据不能进行读写)。缓冲区的限制不能 为负,并且不能大于其容量。 写入模式,限制等于 buffer的容量。读取模式下,limit等于写入的数据量。

位置 (position):下一个要读取或写入的数据的索引。 缓冲区的位置不能为 负,并且不能大于其限制

标记 (mark)与重置 (reset):标记是一个索引, 通过 Buffer 中的 mark() 方法 指定 Buffer 中一个 特定的 position,之后可以通过调用 reset() 方法恢 复到这 个 position.

标记、位置、限制、容量遵守以下不变式: 0 <= mark <= position <= limit <= capacity

在这里插入图片描述

 Buffer常见方法:

  1. Buffer clear() :清空缓冲区并返回对缓冲区的引用
  2. Buffer flip() :为 将缓冲区的界限设置为当前位置, 并将当前位置重置为 0
  3. int capacity() :返回 Buffer 的 capacity 大小
  4. boolean hasRemaining(): 判断缓冲区中是否还有元素
  5. int limit() :返回 Buffer 的界限(limit) 的位置
  6. Buffer limit(int n) 将设置缓冲区界限为 n, 并返回一个具有新 limit 的缓冲区对象
  7. Buffer mark(): 对缓冲区设置标记
  8. int position() :返回缓冲区的当前位置 position
  9. Buffer position(int n) :将设置缓冲区的当前位置为 n, 并返回修改后的 Buffer 对象
  10. int remaining() :返回 position 和 limit 之间的元素个数
  11. Buffer reset() :将位置 position 转到以前设置的mark 所在的位置
  12. Buffer rewind() :将位置设为为 0, 取消设置的 mark

缓冲区的数据操作 Buffer 所有子类提供了两个用于数据操作的方法:

  1. get() :读取单个字节
  2. get(byte[] dst):批量读取多个字节到 dst 中
  3. get(int index):读取指定索引位置的字节(不会移动 position)放到入数据到Buffer中
  4. put(byte b):将给定单个字节写入缓冲区的当前位置
  5. put(byte[] src):将 src 中的字节写入缓冲区的当前位置
  6. put(int index, byte b):将指定字节写入缓冲区的索引 位置(不会移动 position)

使用Buffer读写数据一般遵循以下四个步骤:

  1. 写入数据到Buffer
  2. 调用flip()方法,转换为读取模式
  3. 从Buffer中读取数据
  4. 调用buffer.clear()方法或者buffer.compact()方 法清除缓冲区
  1.   package com.kgf.kgfjavalearning2021.io.nio;
  2.    
  3.   import org.junit.Test;
  4.    
  5.   import java.nio.ByteBuffer;
  6.    
  7.   /***
  8.   * Buffer测试类
  9.   */
  10.   public class TestBuffer {
  11.    
  12.   @Test
  13.   public void test1(){
  14.   //1. 分配一个指定大小的缓冲区
  15.   ByteBuffer buf = ByteBuffer.allocate(1024);
  16.   System.out.println("-----------------allocate()----------------");
  17.   System.out.println(buf.position());// 0: 表示当前的位置为0
  18.   System.out.println(buf.limit());// 1024: 表示界限为1024,前1024个位置是允许我们读写的
  19.   System.out.println(buf.capacity());//1024:表示容量大小为1024
  20.    
  21.   //2. 利用 put() 存入数据到缓冲区中
  22.   System.out.println("-----------------put()----------------");
  23.   String str = "itheima";
  24.   buf.put(str.getBytes());
  25.   System.out.println(buf.position());// 7表示下一个可以写入的位置是7,因为我们写入的字节是7个,从0开始已经写了7个,位置为8的position为7
  26.   System.out.println(buf.limit());// 1024:表示界限为1024,前1024个位置是允许我们读写的
  27.   System.out.println(buf.capacity());//1024:表示容量大小为1024
  28.    
  29.   //3. 切换读取数据模式
  30.   System.out.println("-----------------flip()----------------");
  31.   buf.flip();
  32.   System.out.println(buf.position());// 0: 读取的起始位置为0
  33.   System.out.println(buf.limit());// 7: 表示界限为7,前7个位置有数据可以读取
  34.   System.out.println(buf.capacity());// 1024:表示容量大小为1024
  35.    
  36.   //4. 利用 get() 读取缓冲区中的数据
  37.   System.out.println("-----------------get()----------------");
  38.   byte[] dst = new byte[buf.limit()];//创建一个界限为limit大小的字节数组
  39.   buf.get(dst);//批量将limit大小的字节写入到dst字节数组中
  40.   System.out.println(new String(dst, 0, dst.length));//结果为itheima
  41.    
  42.   System.out.println(buf.position());//7: 读取的位置变为7,因为前面的7个字节数据已经全部读取出去,下一个可读取的位置为7,从0开始的
  43.   System.out.println(buf.limit());//7: 可读取的界限大小为7
  44.   System.out.println(buf.capacity());// 1024: 表示容量大小为1024
  45.    
  46.   //5. rewind() : 可重复读
  47.   System.out.println("-----------------rewind()----------------");
  48.   buf.rewind();// 将位置设为为 0,从头开始读取
  49.   System.out.println(buf.position());// 0
  50.   System.out.println(buf.limit());// 7
  51.   System.out.println(buf.capacity());// 1024
  52.    
  53.   //6. clear() : 清空缓冲区. 但是缓冲区中的数据依然存在,但是处于“被遗忘”状态
  54.   System.out.println("-----------------clear()----------------");
  55.   buf.clear();
  56.   System.out.println(buf.position());// 0
  57.   System.out.println(buf.limit());// 1024
  58.   System.out.println(buf.capacity());// 1024
  59.   System.out.println((char)buf.get());//i
  60.    
  61.   }
  62.    
  63.   @Test
  64.   public void test2(){
  65.   String str = "itheima";
  66.    
  67.   ByteBuffer buf = ByteBuffer.allocate(1024);
  68.    
  69.   buf.put(str.getBytes());// 将str写入到buf缓冲区中
  70.    
  71.   buf.flip();//转换为读模式
  72.    
  73.   byte[] dst = new byte[buf.limit()];//定义一个字节数组
  74.   buf.get(dst, 0, 2);//将前2个字节批量写入到dst字节数组中
  75.   System.out.println(new String(dst, 0, 2));//打印结果为it
  76.   System.out.println(buf.position());//当前下一个读取的位置为2
  77.    
  78.   //mark() : 标记
  79.   buf.mark();
  80.    
  81.   buf.get(dst, 2, 2);//从第3个位置开始将2个字节批量写入到dst字节数组中
  82.   System.out.println(new String(dst, 2, 2));//打印结果为he
  83.   System.out.println(buf.position());// 当前下一个读取的位置为4
  84.    
  85.   //reset() : 恢复到 mark 的位置
  86.   buf.reset();
  87.   System.out.println(buf.position());// 2
  88.    
  89.   //判断缓冲区中是否还有剩余数据
  90.   if(buf.hasRemaining()){
  91.   //获取缓冲区中可以操作的数量
  92.   System.out.println(buf.remaining());// 5: 返回 position 和 limit 之间的元素个数
  93.   }
  94.   }
  95.    
  96.   @Test
  97.   public void test3(){
  98.   //分配直接缓冲区
  99.   ByteBuffer buf = ByteBuffer.allocateDirect(1024);
  100.   System.out.println(buf.isDirect());
  101.   }
  102.    
  103.   }

直接与非直接缓冲区:

byte byffer可以是两种类型,一种是基于直接内存(也就是非堆内存);另一种是非直接内存(也就是堆内存)。对于直接内存来说,JVM将会在IO操作上具有更高的性能,因为它
直接作用于本地系统的IO操作。而非直接内存,也就是堆内存中的数据,如果要作IO操作,会先从本进程内存复制到直接内存,再利用本地IO处理。

从数据流的角度,非直接内存是下面这样的作用链:

本地IO-->直接内存-->非直接内存-->直接内存-->本地IO

而直接内存是:

本地IO-->直接内存-->本地IO

很明显,在做IO处理时,比如网络发送大量数据时,直接内存会具有更高的效率。直接内存使用allocateDirect创建,但是它比申请普通的堆内存需要耗费更高的性能。不过,这部分的数据是在JVM之外的,因此它不会占用应用的内存。所以呢,当你有很大的数据要缓存,并且它的生命周期又很长,那么就比较适合使用直接内存。只是一般来说,如果不是能带来很明显的性能提升,还是推荐直接使用堆内存。字节缓冲区是直接缓冲区还是非直接缓冲区可通过调用其 isDirect()  方法来确定。

使用场景

  1.  有很大的数据需要存储,它的生命周期又很长
  2.  适合频繁的IO操作,比如网络并发场景

五、NIO核心二:通道(Channel)

 1、通道Channe概述

        通道(Channel):由 java.nio.channels 包定义 的。Channel 表示 IO 源与目标打开的连接。 Channel 类似于传统的“流”。只不过 Channel 本身不能直接访问数据,Channel 只能与 Buffer 进行交互。

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

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

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

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

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

4、Channel 在 NIO 中是一个接口

public interface Channel extends Closeable{}

5、常用的Channel实现类

  • FileChannel:用于读取、写入、映射和操作文件的通道。
  • DatagramChannel:通过 UDP 读写网络中的数据通道。
  • SocketChannel:通过 TCP 读写网络中的数据。
  • ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。 【ServerSocketChanne 类似 ServerSocket , SocketChannel 类似 Socket】

6、FileChannel 类

获取通道的一种方式是对支持通道的对象调用getChannel() 方法。支持通道的类如下

  • FileInputStream
  • FileOutputStream
  • RandomAccessFile
  • DatagramSocket
  • Socket
  • ServerSocket
  • 获取通道的其他方式是使用 Files 类的静态方法 newByteChannel() 获取字节通道。或者通过通道的静态方法 open() 打开并返回指定通道

7、FileChannel常用方法

  • int read(ByteBuffer dst) :从Channel 到 中读取数据到  ByteBuffer
  • long  read(ByteBuffer[] dsts) : 将Channel中的数据“分散”到  ByteBuffer[]
  • int  write(ByteBuffer src) :将  ByteBuffer中的数据写入到  Channel
  • long write(ByteBuffer[] srcs) :将  ByteBuffer[] 到 中的数据“聚集”到  Channel
  • long position() :返回此通道的文件位置
  • FileChannel position(long p) :设置此通道的文件位置
  • long size() :返回此通道的文件的当前大小
  • FileChannel truncate(long s) :将此通道的文件截取为给定大小
  • void force(boolean metaData) :强制将所有对此通道的文件更新写入到存储设备中

8、案例1-本地文件写数据

  1.   package com.kgf.kgfjavalearning2021.io.nio;
  2.    
  3.   import org.junit.Test;
  4.    
  5.   import java.io.FileOutputStream;
  6.   import java.nio.ByteBuffer;
  7.   import java.nio.channels.FileChannel;
  8.    
  9.   /***
  10.   * 需求:使用前面学习后的 ByteBuffer(缓冲)和 FileChannel(通道), 将数据写入到 data.txt 中.
  11.   */
  12.   public class ChannelTest {
  13.    
  14.   @Test
  15.   public void write(){
  16.   try {
  17.   // 1、字节输出流通向目标文件
  18.   FileOutputStream fos = new FileOutputStream("E:\\test\\data01.txt");
  19.   // 2、得到字节输出流对应的通道Channel
  20.   FileChannel channel = fos.getChannel();
  21.   // 3、分配缓冲区
  22.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  23.   for (int i = 0; i < 10; i++) {
  24.   buffer.clear();//清空缓冲区
  25.   buffer.put(("hello,使用Buffer和channel实现写数据到文件中"+i+"\r\n").getBytes());
  26.   // 4、把缓冲区切换成写出模式
  27.   buffer.flip();
  28.   channel.write(buffer);//将缓冲区的数据写入到文件通道
  29.   }
  30.   channel.close();
  31.   System.out.println("写数据到文件中!");
  32.   } catch (Exception e) {
  33.   e.printStackTrace();
  34.   }
  35.   }
  36.   }

9、案例2-本地文件读数据

  1.   /***
  2.   * 设置两个缓冲区,一大一小,大的缓冲区为每次读取的量,小的缓冲区存放每行的数据(确保大小可存放文本中最长的那行)。读取的时候判断是不是换行符13,是的话则返回一行数据,不是的话继续读取,直到读完文件。
  3.   * @throws Exception
  4.   */
  5.   @Test
  6.   public void read() throws Exception {
  7.   // 1、定义一个文件字节输入流与源文件接通
  8.   FileInputStream is = new FileInputStream("E:\\test\\data01.txt");
  9.   // 2、需要得到文件字节输入流的文件通道
  10.   FileChannel channel = is.getChannel();
  11.   // 3、定义一个缓冲区
  12.   int bufferSize = 1024 * 1024; // 每一块的大小
  13.   ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
  14.    
  15.   ByteBuffer bb = ByteBuffer.allocate(1024);
  16.    
  17.   // 4、读取数据到缓冲区
  18.   int bytesRead = channel.read(buffer);
  19.   while (bytesRead != -1) {
  20.   buffer.flip();// 切换模式,写->读
  21.   while (buffer.hasRemaining()) {//返回 position 和 limit 之间的元素个数
  22.   byte b = buffer.get();
  23.   if (b == 10 || b == 13) { // 换行或回车
  24.   bb.flip();
  25.   // 这里就是一个行
  26.   final String line = Charset.forName("utf-8").decode(bb).toString();
  27.   System.out.println(line);// 解码已经读到的一行所对应的字节
  28.   bb.clear();
  29.   } else {
  30.   if (bb.hasRemaining())
  31.   bb.put(b);
  32.   else { // 空间不够扩容
  33.   bb = reAllocate(bb);
  34.   bb.put(b);
  35.   }
  36.   }
  37.   }
  38.   buffer.clear();// 清空,position位置为0,limit=capacity
  39.   // 继续往buffer中写
  40.   bytesRead = channel.read(buffer);
  41.   }
  42.   channel.close();
  43.   }

10、案例3-使用Buffer完成文件复制

  1.   /**
  2.   * 使用 FileChannel(通道) ,完成文件的拷贝。
  3.   * @throws Exception
  4.   */
  5.   @Test
  6.   public void copy() throws Exception {
  7.   // 源文件
  8.   File srcFile = new File("E:\\test\\Aurora-4k.jpg");
  9.   File destFile = new File("E:\\test\\Aurora-4k-new.jpg");
  10.   // 得到一个字节字节输入流
  11.   FileInputStream fis = new FileInputStream(srcFile);
  12.   // 得到一个字节输出流
  13.   FileOutputStream fos = new FileOutputStream(destFile);
  14.   // 得到的是文件通道
  15.   FileChannel isChannel = fis.getChannel();
  16.   FileChannel osChannel = fos.getChannel();
  17.   // 分配缓冲区
  18.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  19.   while(isChannel.read(buffer)>0){
  20.   // 已经读取了数据 ,把缓冲区的模式切换成可读模式
  21.   buffer.flip();
  22.   // 把数据写出到
  23.   osChannel.write(buffer);//将buffer缓冲区中的数据写入到osChannel中
  24.   // 必须先清空缓冲然后再写入数据到缓冲区
  25.   buffer.clear();
  26.   }
  27.   isChannel.close();
  28.   osChannel.close();
  29.   System.out.println("复制完成!");
  30.   }

11、案例4-transferFrom()

从目标通道中去复制原通道数据

  1.   @Test
  2.   public void test02() throws Exception {
  3.   // 1、字节输入管道
  4.   FileInputStream is = new FileInputStream("E:\\test\\Aurora-4k.jpg");
  5.   FileChannel isChannel = is.getChannel();
  6.   // 2、字节输出流管道
  7.   FileOutputStream fos = new FileOutputStream("E:\\test\\Aurora-4knew3.jpg");
  8.   FileChannel osChannel = fos.getChannel();
  9.   // 3、复制
  10.   osChannel.transferFrom(isChannel,isChannel.position(),isChannel.size());
  11.   isChannel.close();
  12.   osChannel.close();
  13.   }

12、案例5-transferTo()

把原通道数据复制到目标通道

  1.   @Test
  2.   public void test03() throws Exception {
  3.   // 1、字节输入管道
  4.   FileInputStream is = new FileInputStream("E:\\test\\Aurora-4k.jpg");
  5.   FileChannel isChannel = is.getChannel();
  6.   // 2、字节输出流管道
  7.   FileOutputStream fos = new FileOutputStream("E:\\test\\Aurora-4knew4.jpg");
  8.   FileChannel osChannel = fos.getChannel();
  9.   // 3、复制
  10.   isChannel.transferTo(isChannel.position() , isChannel.size() , osChannel);
  11.   isChannel.close();
  12.   osChannel.close();
  13.   }

13、案例6-分散 (Scatter) 和聚集 (Gather)

  • 分散读取(Scatter ):是指把Channel通道的数据读入到 多个缓冲区中去
  • 聚集写入(Gathering )是指将多个 Buffer 中的数 据“聚集”到 Channel。
  1.   //分散和聚集
  2.   @Test
  3.   public void test() throws IOException{
  4.   RandomAccessFile raf1 = new RandomAccessFile("1.txt", "rw");
  5.   //1. 获取通道
  6.   FileChannel channel1 = raf1.getChannel();
  7.    
  8.   //2. 分配指定大小的缓冲区
  9.   ByteBuffer buf1 = ByteBuffer.allocate(100);
  10.   ByteBuffer buf2 = ByteBuffer.allocate(1024);
  11.    
  12.   //3. 分散读取
  13.   ByteBuffer[] bufs = {buf1, buf2};
  14.   channel1.read(bufs);
  15.    
  16.   for (ByteBuffer byteBuffer : bufs) {
  17.   byteBuffer.flip();
  18.   }
  19.    
  20.   System.out.println(new String(bufs[0].array(), 0, bufs[0].limit()));
  21.   System.out.println("-----------------");
  22.   System.out.println(new String(bufs[1].array(), 0, bufs[1].limit()));
  23.    
  24.   //4. 聚集写入
  25.   RandomAccessFile raf2 = new RandomAccessFile("2.txt", "rw");
  26.   FileChannel channel2 = raf2.getChannel();
  27.    
  28.   channel2.write(bufs);
  29.   }

六、NIO核心三:选择器(Selector)

1、选择器(Selector)概述

        选择器(Selector)是SelectableChannle对象的多路复用器,Selector可以同时监控多个SelectableChannel的IO状况,也就是说,利用Selector可使一个单独的线程管理多个Channel。Selector是非阻塞IO的核心。

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

2、选择器的应用

创建 Selector :通过调用 Selector.open() 方法创建一个 Selector。

Selector selector = Selector.open();

向选择器注册通道:SelectableChannel.register(Selector sel, int ops)

  1.   //1. 获取通道
  2.   ServerSocketChannel ssChannel = ServerSocketChannel.open();
  3.   //2. 切换非阻塞模式
  4.   ssChannel.configureBlocking(false);
  5.   //3. 绑定连接
  6.   ssChannel.bind(new InetSocketAddress(9898));
  7.   //4. 获取选择器
  8.   Selector selector = Selector.open();
  9.   //5. 将通道注册到选择器上, 并且指定“监听接收事件”
  10.   ssChannel.register(selector, SelectionKey.OP_ACCEPT);

当调用 register(Selector sel, int ops) 将通道注册选择器时,选择器对通道的监听事件,需要通过第二个参数 ops 指定。可以监听的事件类型(用 可使用 SelectionKey 的四个常量 表示):

  • 读 : SelectionKey.OP_READ (1)
  • 写 : SelectionKey.OP_WRITE (4)
  • 连接 : SelectionKey.OP_CONNECT (8)
  • 接收 : SelectionKey.OP_ACCEPT (16)

若注册时不止监听一个事件,则可以使用“位或”操作符连接。
int interestSet = SelectionKey.OP_READ|SelectionKey.OP_WRITE


3、NIO非阻塞式网络通信原理分析

3.1、Selector 示意图和特点说明

        Selector可以实现: 一个 I/O 线程可以并发处理 N 个客户端连接和读写操作,这从根本上解决了传统同步阻塞 I/O 一连接一线程模型,架构的性能、弹性伸缩能力和可靠性都得到了极大的提升。

在这里插入图片描述

3.2、服务端流程

 1)、获取通道。当客户端连接服务端时,服务端会通过 ServerSocketChannel 得到 SocketChannel:

 ServerSocketChannel ssChannel = ServerSocketChannel.open();

2)、切换非阻塞模式

 ssChannel.configureBlocking(false);

3)、绑定连接

 ssChannel.bind(new InetSocketAddress(8888));

4)、获取选择器

Selector selector = Selector.open();

5)、将通道注册到选择器上, 并且指定“监听接收事件”

ssChannel.register(selector, SelectionKey.OP_ACCEPT);

6)、轮询式的获取选择器上已经“准备就绪”的事件

  1.   while (selector.select() > 0){
  2.   System.out.println("开启事件处理");
  3.   //7.获取选择器中所有注册的通道中已准备好的事件
  4.   Iterator<SelectionKey> it = selector.selectedKeys().iterator();
  5.   //8.开始遍历事件
  6.   while (it.hasNext()){
  7.   SelectionKey selectionKey = it.next();
  8.   System.out.println("--->"+selectionKey);
  9.   //9.判断这个事件具体是啥
  10.   if (selectionKey.isAcceptable()){
  11.   //10.获取当前接入事件的客户端通道
  12.   SocketChannel socketChannel = serverSocketChannel.accept();
  13.   //11.切换成非阻塞模式
  14.   socketChannel.configureBlocking(false);
  15.   //12.将本客户端注册到选择器
  16.   socketChannel.register(selector,SelectionKey.OP_READ);
  17.   }else if (selectionKey.isReadable()){
  18.   //13.获取当前选择器上的读
  19.   SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
  20.   //14.读取
  21.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  22.   int len;
  23.   while ((len = socketChannel.read(buffer)) > 0){
  24.   buffer.flip();
  25.   System.out.println(new String(buffer.array(),0,len));
  26.   //清除之前的数据(覆盖写入)
  27.   buffer.clear();
  28.   }
  29.   }
  30.   //15.处理完毕后,移除当前事件
  31.   it.remove();
  32.   }
  33.   }

3.3、客户端流程

1)、获取通道

SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));

2)、切换非阻塞模式

sChannel.configureBlocking(false);

3)、分配指定大小的缓冲区

ByteBuffer buffer = ByteBuffer.allocate(1024);

4)、发送数据给绑定的服务端

  1.   Scanner scan = new Scanner(System.in);
  2.   while(scan.hasNext()){
  3.   String str = scan.nextLine();
  4.   buf.put((new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(System.currentTimeMillis())
  5.   + "\n" + str).getBytes());
  6.   buf.flip();
  7.   sChannel.write(buf);
  8.   buf.clear();
  9.   }
  10.   //关闭通道
  11.   sChannel.close();

4、NIO非阻塞式网络通信入门案例

需求:服务端接收客户端的连接请求,并接收多个客户端发送过来的事件。

Server端代码实现:

  1.   package nio.ss;
  2.    
  3.   import java.io.IOException;
  4.   import java.net.InetSocketAddress;
  5.   import java.nio.ByteBuffer;
  6.   import java.nio.channels.*;
  7.   import java.util.Iterator;
  8.    
  9.   public class Server {
  10.   public static void main(String[] args) {
  11.   try {
  12.   //1.获取管道
  13.   ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
  14.   //2.设置非阻塞模式
  15.   serverSocketChannel.configureBlocking(false);
  16.   //3.绑定端口
  17.   serverSocketChannel.bind(new InetSocketAddress(8888));
  18.   //4.获取选择器
  19.   Selector selector = Selector.open();
  20.   //5.将通道注册到选择器上,并且开始指定监听的接收事件
  21.   serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
  22.   //6.轮询已经就绪的事件
  23.   while (selector.select() > 0){
  24.   System.out.println("开启事件处理");
  25.   //7.获取选择器中所有注册的通道中已准备好的事件
  26.   Iterator<SelectionKey> it = selector.selectedKeys().iterator();
  27.   //8.开始遍历事件
  28.   while (it.hasNext()){
  29.   SelectionKey selectionKey = it.next();
  30.   System.out.println("--->"+selectionKey);
  31.   //9.判断这个事件具体是啥
  32.   if (selectionKey.isAcceptable()){
  33.   //10.获取当前接入事件的客户端通道
  34.   SocketChannel socketChannel = serverSocketChannel.accept();
  35.   //11.切换成非阻塞模式
  36.   socketChannel.configureBlocking(false);
  37.   //12.将本客户端注册到选择器
  38.   socketChannel.register(selector,SelectionKey.OP_READ);
  39.   }else if (selectionKey.isReadable()){
  40.   //13.获取当前选择器上的读
  41.   SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
  42.   //14.读取
  43.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  44.   int len;
  45.   while ((len = socketChannel.read(buffer)) > 0){
  46.   buffer.flip();
  47.   System.out.println(new String(buffer.array(),0,len));
  48.   //清除之前的数据(覆盖写入)
  49.   buffer.clear();
  50.   }
  51.   }
  52.   //15.处理完毕后,移除当前事件
  53.   it.remove();
  54.   }
  55.   }
  56.   } catch (IOException e) {
  57.   e.printStackTrace();
  58.   }
  59.   }
  60.   }

Client端代码实现:

  1.   package nio.ss;
  2.    
  3.   import java.io.IOException;
  4.   import java.net.InetSocketAddress;
  5.   import java.nio.ByteBuffer;
  6.   import java.nio.channels.SocketChannel;
  7.   import java.util.Scanner;
  8.    
  9.   public class Client {
  10.   public static void main(String[] args) {
  11.   try {
  12.   SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8888));
  13.   socketChannel.configureBlocking(false);
  14.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  15.   Scanner scanner = new Scanner(System.in);
  16.   while (true){
  17.   System.out.print("请输入:");
  18.   String msg = scanner.nextLine();
  19.   buffer.put(msg.getBytes());
  20.   buffer.flip();
  21.   socketChannel.write(buffer);
  22.   buffer.clear();
  23.   }
  24.   } catch (IOException e) {
  25.   e.printStackTrace();
  26.   }
  27.   }
  28.   }

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

需求:进一步理解 NIO 非阻塞网络编程机制,实现多人群聊

  • 编写一个 NIO 群聊系统,实现客户端与客户端的通信需求(非阻塞)
  • 服务器端:可以监测用户上线,离线,并实现消息转发功能
  • 客户端:通过 channel 可以无阻塞发送消息给其它所有客户端用户,同时可以接受其它客户端用户通过服务端转发来的消息

服务端代码:

  1.   package nio.chat;
  2.    
  3.   import java.io.IOException;
  4.   import java.net.InetSocketAddress;
  5.   import java.nio.ByteBuffer;
  6.   import java.nio.channels.*;
  7.   import java.util.Iterator;
  8.    
  9.   /**
  10.   *
  11.   */
  12.   public class Server {
  13.   //定义属性
  14.   private Selector selector;
  15.   private ServerSocketChannel ssChannel;
  16.   private static final int PORT = 9999;
  17.   //构造器
  18.   //初始化工作
  19.   public Server() {
  20.   try {
  21.   // 1、获取通道
  22.   ssChannel = ServerSocketChannel.open();
  23.   // 2、切换为非阻塞模式
  24.   ssChannel.configureBlocking(false);
  25.   // 3、绑定连接的端口
  26.   ssChannel.bind(new InetSocketAddress(PORT));
  27.   // 4、获取选择器Selector
  28.   selector = Selector.open();
  29.   // 5、将通道都注册到选择器上去,并且开始指定监听接收事件
  30.   ssChannel.register(selector , SelectionKey.OP_ACCEPT);
  31.   }catch (IOException e) {
  32.   e.printStackTrace();
  33.   }
  34.   }
  35.   //监听
  36.   public void listen() {
  37.   System.out.println("监听线程:" + Thread.currentThread().getName());
  38.   try {
  39.   while (selector.select() > 0){
  40.   // 7、获取选择器中的所有注册的通道中已经就绪好的事件
  41.   Iterator<SelectionKey> it = selector.selectedKeys().iterator();
  42.   // 8、开始遍历这些准备好的事件
  43.   while (it.hasNext()){
  44.   // 提取当前这个事件
  45.   SelectionKey sk = it.next();
  46.   // 9、判断这个事件具体是什么
  47.   if(sk.isAcceptable()){
  48.   // 10、直接获取当前接入的客户端通道
  49.   SocketChannel schannel = ssChannel.accept();
  50.   // 11 、切换成非阻塞模式
  51.   schannel.configureBlocking(false);
  52.   // 12、将本客户端通道注册到选择器
  53.   System.out.println(schannel.getRemoteAddress() + " 上线 ");
  54.   schannel.register(selector , SelectionKey.OP_READ);
  55.   //提示
  56.   }else if(sk.isReadable()){
  57.   //处理读 (专门写方法..)
  58.   readData(sk);
  59.   }
  60.    
  61.   it.remove(); // 处理完毕之后需要移除当前事件
  62.   }
  63.   }
  64.   }catch (Exception e) {
  65.   e.printStackTrace();
  66.   }finally {
  67.   //发生异常处理....
  68.    
  69.   }
  70.   }
  71.    
  72.   //读取客户端消息
  73.   private void readData(SelectionKey key) {
  74.   //获取关联的channel
  75.   SocketChannel channel = null;
  76.   try {
  77.   //得到channel
  78.   channel = (SocketChannel) key.channel();
  79.   //创建buffer
  80.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  81.   int count = channel.read(buffer);
  82.   //根据count的值做处理
  83.   if(count > 0) {
  84.   //把缓存区的数据转成字符串
  85.   String msg = new String(buffer.array());
  86.   //输出该消息
  87.   System.out.println("来自客户端---> " + msg);
  88.   //向其它的客户端转发消息(去掉自己), 专门写一个方法来处理
  89.   sendInfoToOtherClients(msg, channel);
  90.   }
  91.   }catch (IOException e) {
  92.   try {
  93.   System.out.println(channel.getRemoteAddress() + " 离线了..");
  94.   e.printStackTrace();
  95.   //取消注册
  96.   key.cancel();
  97.   //关闭通道
  98.   channel.close();
  99.   }catch (IOException e2) {
  100.   e2.printStackTrace();;
  101.   }
  102.   }
  103.   }
  104.    
  105.   //转发消息给其它客户(通道)
  106.   private void sendInfoToOtherClients(String msg, SocketChannel self ) throws IOException{
  107.   System.out.println("服务器转发消息中...");
  108.   System.out.println("服务器转发数据给客户端线程: " + Thread.currentThread().getName());
  109.   //遍历 所有注册到selector 上的 SocketChannel,并排除 self
  110.   for(SelectionKey key: selector.keys()) {
  111.   //通过 key 取出对应的 SocketChannel
  112.   Channel targetChannel = key.channel();
  113.   //排除自己
  114.   if(targetChannel instanceof SocketChannel && targetChannel != self) {
  115.   //转型
  116.   SocketChannel dest = (SocketChannel)targetChannel;
  117.   //将msg 存储到buffer
  118.   ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
  119.   //将buffer 的数据写入 通道
  120.   dest.write(buffer);
  121.   }
  122.   }
  123.   }
  124.    
  125.   public static void main(String[] args) {
  126.   //创建服务器对象
  127.   Server groupChatServer = new Server();
  128.   groupChatServer.listen();
  129.   }
  130.   }

客户端代码:

  1.   package nio.chat;
  2.    
  3.   import java.io.IOException;
  4.   import java.net.InetSocketAddress;
  5.   import java.nio.ByteBuffer;
  6.   import java.nio.channels.SelectionKey;
  7.   import java.nio.channels.Selector;
  8.   import java.nio.channels.SocketChannel;
  9.   import java.util.Iterator;
  10.   import java.util.Scanner;
  11.    
  12.   public class Client {
  13.   //定义相关的属性
  14.   private final String HOST = "127.0.0.1"; // 服务器的ip
  15.   private final int PORT = 9999; //服务器端口
  16.   private Selector selector;
  17.   private SocketChannel socketChannel;
  18.   private String username;
  19.    
  20.   //构造器, 完成初始化工作
  21.   public Client() throws IOException {
  22.   selector = Selector.open();
  23.   //连接服务器
  24.   socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
  25.   //设置非阻塞
  26.   socketChannel.configureBlocking(false);
  27.   //将channel 注册到selector
  28.   socketChannel.register(selector, SelectionKey.OP_READ);
  29.   //得到username
  30.   username = socketChannel.getLocalAddress().toString().substring(1);
  31.   System.out.println(username + " is ok...");
  32.   }
  33.    
  34.   //向服务器发送消息
  35.   public void sendInfo(String info) {
  36.   info = username + " 说:" + info;
  37.   try {
  38.   socketChannel.write(ByteBuffer.wrap(info.getBytes()));
  39.   }catch (IOException e) {
  40.   e.printStackTrace();
  41.   }
  42.   }
  43.    
  44.   //读取从服务器端回复的消息
  45.   public void readInfo() {
  46.   try {
  47.   int readChannels = selector.select();
  48.   if(readChannels > 0) {//有可以用的通道
  49.    
  50.   Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
  51.   while (iterator.hasNext()) {
  52.    
  53.   SelectionKey key = iterator.next();
  54.   if(key.isReadable()) {
  55.   //得到相关的通道
  56.   SocketChannel sc = (SocketChannel) key.channel();
  57.   //得到一个Buffer
  58.   ByteBuffer buffer = ByteBuffer.allocate(1024);
  59.   //读取
  60.   sc.read(buffer);
  61.   //把读到的缓冲区的数据转成字符串
  62.   String msg = new String(buffer.array());
  63.   System.out.println(msg.trim());
  64.   }
  65.   }
  66.   iterator.remove(); //删除当前的selectionKey, 防止重复操作
  67.   } else {
  68.   //System.out.println("没有可以用的通道...");
  69.   }
  70.   }catch (Exception e) {
  71.   e.printStackTrace();
  72.   }
  73.   }
  74.    
  75.   public static void main(String[] args) throws Exception {
  76.   //启动我们客户端
  77.   Client chatClient = new Client();
  78.   //启动一个线程, 每个3秒,读取从服务器发送数据
  79.   new Thread() {
  80.   public void run() {
  81.   while (true) {
  82.   chatClient.readInfo();
  83.   try {
  84.   Thread.currentThread().sleep(3000);
  85.   }catch (InterruptedException e) {
  86.   e.printStackTrace();
  87.   }
  88.   }
  89.   }
  90.   }.start();
  91.    
  92.   //发送数据给服务器端
  93.   Scanner scanner = new Scanner(System.in);
  94.   while (scanner.hasNextLine()) {
  95.   String s = scanner.nextLine();
  96.   chatClient.sendInfo(s);
  97.   }
  98.   }
  99.   }

 


七、AIO 深入剖析

Java AIO(NIO.2) : 异步非阻塞,服务器实现模式为一个有效请求一个线程,客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理。

  1.   AIO:异步非阻塞,基于NIO的,可以称之为NIO2.0
  2.    
  3.   BIO NIO AIO
  4.   Socket SocketChannel AsynchronousSocketChannel
  5.   ServerSocket ServerSocketChannel AsynchronousServerSocketChannel

与NIO不同,当进行读写操作时,只须直接调用API的read或write方法即可, 这两种方法均为异步的,对于读操作而言,当有流可读取时,操作系统会将可读的流传入read方法的缓冲区,对于写操作而言,当操作系统将write方法传递的流写入完毕时,操作系统主动通知应用程序

即可以理解为,read/write方法都是异步的,完成后会主动调用回调函数。在JDK1.7中,这部分内容被称作NIO.2,主要在Java.nio.channels包下增加了下面四个异步通道:

  • AsynchronousSocketChannel
  • ​ AsynchronousServerSocketChannel
  • ​ AsynchronousFileChannel
  • ​ AsynchronousDatagramChannel

八、总结

BIO、NIO、AIO:

  • Java BIO : 同步并阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,当然可以通过线程池机制改善。
  • Java NIO : 同步非阻塞,服务器实现模式为一个请求一个线程,即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求时才启动一个线程进行处理。
  • Java AIO(NIO.2) : 异步非阻塞,服务器实现模式为一个有效请求一个线程,客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理。

BIO、NIO、AIO适用场景分析:

  • BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,但程序直观简单易理解。
  • NIO方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,并发局限于应用中,编程比较复杂,JDK1.4开始支持。
  • AIO方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用OS参与并发操作,编程比较复杂,JDK7开始支持。Netty!

标签:java,NIO,简介,System,println,ByteBuffer,缓冲区,通道,out
From: https://www.cnblogs.com/gaoyanbing/p/17287299.html

相关文章

  • Java——Java8 新特性原理与实践
    摘要主要是的介绍一下JDK1.8的相关的新特性的知识,同时将JDK1.8新特性的代码开源在个人的github中,如果有需要参考的话请在:Senior-Architect/java语言基础atmaster·2462612540/Senior-Architect·GitHub一、接口内允许添加默认实现的方法Java8允许我们通过default关键字对......
  • java.secunty.AccessControException: the Permission java.io.FilePermission /hom
     利用oracle的java写入服务器的文件夹文件的时候会出现类似这种报错,看到报错我们可以猜到是关于权限的问题。   只需要利用sys用户在sqlplus或者plsql的命令行模式下执行下列代码就使得对应用户获得对应目录的读、写、删的权限了。 execdbms_java.grant_permissio......
  • 系统化学习前端之JavaScript(ES6:异步编程)
    前言JavaScript异步编程这块东西比较多,涉及到宏任务和微任务,所以单开一个篇幅梳理一下。同步和异步同步和异步是一种宏观概念,具体表现在JavaScript中,是同步任务和异步任务,即同步函数和异步函数。同步同步指函数在JavaScript同步执行。同步函数执行过程:A函数进入函数调......
  • Java:如何在PowerPoint幻灯片中创建散点图
    散点图是通过两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。散点图将序列显示为一组点,值由点在图表中的位置表示,类别由图表中的不同标记表示,通常用于比较跨类别的聚合数据。本文将为您介如何通过Java代码在PowerPoint幻灯片中创建......
  • 学了这么久的高并发编程,连Java中的并发原子类都不知道?
    摘要:保证线程安全是Java并发编程必须要解决的重要问题,本文和大家聊聊Java中的并发原子类,看它如何确保多线程的数据一致性。本文分享自华为云社区《学了这么久的高并发编程,连Java中的并发原子类都不知道?这也太Low了吧》,作者:冰河。今天我们一起来聊聊Java中的并发原子类。在 j......
  • java virtual thread
    Avirtualthreadisaninstanceofjava.lang.ThreadthatisnottiedtoaparticularOSthread.Aplatformthread,bycontrast,isaninstanceofjava.lang.Threadimplementedinthetraditionalway,asathinwrapperaroundanOSthread.Applicationcode......
  • 剩余使用寿命RUL预测技术---简介
    剩余使用寿命(Remainingusefullife,即RUL)预测技术是预测与健康管理(PHM)的关键技术。它主要是评估设备的性能状态,指导人们对设备进行更换或维修设备,有效避免由于机器故障而导致的安全问题和经济损失。通过阅读综述和研究型文献,剩余使用寿命(Remainingusefullife,即RUL)预测......
  • dubbo线程池又被打爆(打满)了java.util.concurrent.RejectedExecutionException: Thread
    转载:https://blog.csdn.net/kevin_mails/article/details/121764780?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-121764780-blog-124236206.235%5Ev27%5Epc_relevant_recovery_v2&depth_1-utm_sourc......
  • wordpress粘贴图片自动上传到服务器(Java版)
    ​ 这种方法是servlet,编写好在web.xml里配置servlet-class和servlet-mapping即可使用后台(服务端)java服务代码:(上传至ROOT/lqxcPics文件夹下)<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@     page contentType="text/html;cha......
  • mvn的简介、安装、使用及常用命令
    一、简介nvm是一个node的版本管理工具,可以简单操作node版本的切换、安装、查看等,与npm不同的是,npm是依赖包的管理工具,nvm是nodejs的版本管理工具,通过它可以安装和切换不同版本的nodejs。 二、安装可以在GitHub上下载最新版本。nvm-noinstall.zip:绿色免安装版,但......