第三章 第一节JavaNIO编程

1. Java NIO基本介绍

  1. Java NIO(Non-blocking IO)指JDK提供新的API.从JDK1.4开始,java提供了一系列改进IO的新特性,被统称为NIO,是同步非阻塞的。
  2. NIO相关类和接口都放在java.nio包及其子包下面,并且对java.io包中很多类进行了改写。
  3. NIO有三大核心部分:Channel(通道), Buffer(缓冲区), Selector(选择器)
  4. NIO是面向缓冲区的。数据读取到一个稍后处理的缓冲区中去,需要的时候可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用他可以提供非阻塞性的高伸缩性网络。
  5. Java NIO的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果么有数据可读,就什么也不用处理,而不是保持线程阻塞,该线程可以做其他的事情。
  6. NIO可以一个线程处理多个操作。1000个请求过来,分配50-100个线程处理就够了,不需要像NIO那样,非得分配1000个。
  7. HTTP2.0 使用了多路复用技术,一个连接并发处理多个请求。

2. NIO和BIO的比较

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

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

在这里插入图片描述
一张图描述NIO中selector和channel和buffer的关系。
说明:

  1. 每个channel都会对应一个buffer
  2. 一个线程对应一个selector,对应多个channel(连接)
  3. 该图反应了有三个channel注册到selector
  4. 线程切到哪个channel是事件event决定的。
  5. selector根据不同的事件在通道上切换
  6. channel是双向的,可以返回底层操作系统的情况,比如linux,底层的os通道就是双向的。
  7. buffer就是一个内存块,底层是一个数组。
  8. 数据的读写是通过buffer。读写切换通过flip.

4. 缓冲区(Buffer)

4.1 基本介绍

缓存区就是一个可以读写数据的内存块,理解为一个容器对象,对象提供了一组方法,可以方便操作内存块,能够跟踪记录缓存区的状态变化情况。channel提供了从文件,网络读取数据的渠道,但是读取或者写入的数据都必须经过buffer.

4.2 buffer类和其子类

在这里插入图片描述

5. 通道(Channel)

5.1 基本介绍

  1. 通道类似于流,有些区别如下:
    • 通道可以同时进行读写,而流只能读或者只能写
    • 通道可以实现异步读写数据
    • 通道可以从缓冲读数据,也可以写数据到缓冲:
      在这里插入图片描述
  2. BIO 中的 stream 是单向的,例如 FileInputStream 对象只能进行读取数据的操作,而 NIO 中的通道(Channel)是双向的,可以读操作,也可以写操作。
  3. 常用的 Channel 类有:FileChannel、DatagramChannel、ServerSocketChannel 和 SocketChannel。【ServerSocketChanne 类似 ServerSocket , SocketChannel 类似 Socket】
  4. FileChannel 用于文件的数据读写,DatagramChannel 用于 UDP 的数据读写,ServerSocketChannel 和 SocketChannel 用于 TCP 的数据读写。
    在这里插入图片描述
    ByteBuffer我们用的比较多:
    在这里插入图片描述

5.2 FileChannel

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

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

5.2.1 实例1-本地文件写数据

使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道), 将 “hello,尚硅谷” 写入到file01.txt 中
流程:

  1. ByteBuffer对象中写入"hello,尚硅谷"。
  2. FileOutputStream关联文件夹,并获取channel对象
  3. 将bytebuffer写入到channel中(写入channel就自动写入到文件了)
    注:Channel可以看做是流包装的对象,见下图。
    在这里插入图片描述
    代码:
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 真实 类型是  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);//写入channel就自动就写入文件里了。
        fileOutputStream.close();
    }
}

5.2.2 实例2-本地文件读数据

使用前面学习后的ByteBuffer(缓冲) 和 FileChannel(通道), 将 file01.txt 中的数据读入到程序,并显示在控制台屏幕
流程:

  1. FileInputStream关联文件夹,并获取到channel
  2. 定义bytebuffer用来读取channel中的值,放到bytebuffer中
  3. 通过bytebuffer转换为string输出
    代码:
    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();
    }

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

使用 FileChannel(通道) 和 方法 read , write,完成文件的拷贝。将file1.txt拷贝file2.txt
流程:

  1. 通过FileInputStream关联file1.txt,并获取channel1
  2. 通过FileOutputStream关联file2.txt,并获取channel2
  3. 循环
  • 读取前清空bytebuffer
  • 读取channel1的内容,读取大小为bytebuffer申请的大小:channel1.read(bytebuffer)
  • bytebuffer.flip() 从写模式转化到读模式
  • 将读取到bytebuffer中的内容写入到channel2中去:channel2.write(bytebuffer)
    代码:
 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因为之前是读状态,postion = limit。再写会导致read = 0。因此用clear重置position
            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();
    }

5.2.4 实例4-拷贝文件transferFrom 方法

使用 FileChannel(通道) 和 方法 transferFrom ,完成文件的拷贝。a.jpg拷贝到b.jpg
流程:

  1. FileInputStream关联a.jpg,获取sourceChannel
  2. FileOutputStream关联b.jpg,获取DesChannel
  3. DesChannel.transferFrom(sourceChannel, 0, sourceChannel.size()) 完成拷贝
    代码:
    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();
    }

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

5.3.1 bytebuffer支持类型化的put和get,put放入的是什么数据类型,get就应该使用相应的数据读出。

//创建一个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());

5.3.2 可以将只读buffer抓换为只读buffer

    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
    }

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

        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("修改成功~~");

5.3.4 NIO 还支持 通过多个Buffer (即 Buffer 数组) 完成读写操作,即 Scattering 和 Gathering

		//使用 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);
        }

6. 选择器(selector)

6.1 基本介绍

  1. Java的NIO可以用非阻塞的IO方式。可以用一个线程处理多个客户端的请求,就会用到selector.
  2. selector检测到注册的多个通道是否有事件发生(注意:多个channel以事件的形式注册到selector),如果有事件发生,获取对应的事件进行处理。这样一个线程通过一个selector管理多个通道(多个连接请求)
  3. 只有在连接通道有读写事件发生的时候才会读写,大大减少了系统开销。并且不需要为每一个连接创建一个线程,不用去维护多个线程。
  4. 避免了多个线程上下文切换导致的开销。

6.2 示意图和特点说明

在这里插入图片描述
说明:

  1. netty的IO线程聚合了selector,可以同时处理上千个客户端连接。
  2. 当线程从客户端socketchannel进行读写数据时,如果没有数据可用,该线程可以进行其他任务
  3. 线程将非阻塞的io的空闲时间用于其他通道执行io操作,所以单独的线程可以处理多个客户端
  4. 读写都是非阻塞的,充分提高了io线程的运行效率
  5. 一个io线程处理多个客户端的请求。从根本上解决了传统阻塞型io一线程一连接模型,架构的性能,可靠性得到了极大提升。

6.3 selector类相关方法

selector是一个抽象类

public abstract class Selector implements Closeable { 
public static Selector open();//得到一个选择器对象
public int select(long timeout);//监控所有注册的通道,当其中有 IO 操作可以进行时,将对应的 SelectionKey 加入到内部集合中并返回,参数用来设置超时时间
public Set<SelectionKey> selectedKeys();//从内部集合中得到所有的 SelectionKey,也就是发生事件的selectKey
}
selector.select()//阻塞,直到获取到有事件发生的selectkey
selector.select(1000);//阻塞1000毫秒,在1000毫秒后返回
selector.wakeup();//唤醒selector
selector.selectNow();//不阻塞,立马返还

6.4 NIO非阻塞原理分析(加入了selector细致分析)

在这里插入图片描述
上图的说明:
以selector为中心:

  1. serverSocketChannel注册到selector上,事件为accept,表示监听客户端连接
  2. 客户端连接的时候selector 会监听,通过selectKeys方法得到所有的selectKey。判断selectKey是否isAcceptable,如果是就获取客户端的socketChannel.
  3. 获取到客户端的channel后同样注册到selector上,注册操作师读操作。如果selectKey是isReadable,就获取socketChannel进行业务处理

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

6.5.1 案例要求

案例要求:
编写一个 NIO 入门案例,实现服务器端和客户端之间的数据简单通讯(非阻塞)
目的:理解NIO非阻塞网络编程机制
看老师代码演示

6.5.2 流程

服务端:
  1. 实例化serverSocketChannel并绑定端口6666, 设置为非阻塞。实例化selector对象。将serverSocketChannel注册到selector中,注册事件为OP_ACCEPT
  2. 循环等待客户端连接
    • selector的select(1s)方法看有无事件发生。无事件发生一直循环
    • 如果有事件发生,获取selectedKeys,遍历selectedKey。
      • 判断是否是Acceptable事件。如果是,serverSocektChannel accept到一个客户端的socketChannel。将其注册到selector中,注册事件为OP_READABLE.
      • 因为selector新注册了客户端读事件,要新增判断条件,如果selectKey是isReadable通过key获取到channe进行读取操作。
      • 循环过程中记得移除遍历过的selectedKey
客户端:
  1. 实例化socketChannel,连接服务器
  2. 如果连接成功了,就往socetChannel写入数据(相当于发送了数据)

6.5.3 代码

服务端代码:

public class NIOServer {
    public static void main(String[] args) throws Exception{
        //创建ServerSocketChannel -> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个Selecor对象
        Selector selector = Selector.open();
        //绑定一个端口6666, 在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //把 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();
            }
        }
    }
}

客户端代码:

public class NIOClient {
    public static void main(String[] args) throws Exception{
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //提供服务器端的ip 和 端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //连接服务器
        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();
    }
}

6.6 案例中相关类说明

6.6.1 SelectionKey

表示selector和网络通道的注册关系。通过key可以获取到channel.
注册关系分为下面四种:
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);//设置或改变监听事件.比如原来是accept现在可以改为read事件
	public final boolean isAcceptable();//是否可以 accept
	public final boolean isReadable();//是否可以读
	public final boolean isWritable();//是否可以写
}

6.6.2 ServerSocketChannel

在服务端监听新的客户端连接
相关方法:

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)//注册一个选择器并设置监听事件
}

6.6.2 SocketChannel

网络IOchannel,负责进行读写操作。可以将数据读或写入通道。

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();//关闭通道
}
  • 17
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值