三、Java NIO编程

3.1 Java NIO基本介绍

在这里插入图片描述

3.2 BIO 和 NIO的比较

  • bio以流的方式处理数据,而NIO以块的方式处理数据,块IO的效率比流IO高很多
  • BIO是阻塞的,NIO是非阻塞的
  • 对于BIO,服务器中的一个线程对应一个client;对于NIO,服务器中的一个线程对应多个客户端

3.3 NIO三大核心 selector、channel、buffer之间的关系

一张图描述 NIO 的 Selector 、 Channel 和 Buffer 的关系:
在这里插入图片描述
在这里插入图片描述

3.4 缓冲区(Buffer)

1 基本介绍

Buffer(缓冲区): 缓冲区本质上是一个可以读写数据的内存块,可以理解成一个容器,该容器提供了一组方法,可以更轻松的使用内存块。缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变换。

Channel提供从文件、网络读取数据的渠道,但是读取或者写入的数据都必须经过Buffer
在这里插入图片描述

2 Buffer类及其子类

在nio中,Buffer是一个顶层父类,他是一个抽象类,类的层级关系如下:
在这里插入图片描述

buffer类中定义了四个属性来表示其包含的数据元素的信息
在这里插入图片描述

3.5 通道

0、 channel基本介绍

  • NIO的通道类似于流,但又有些区别

    • 通道可以同时进行读写,而流只能读或者写
    • 通道可以从缓冲读数据,也可以写数据到缓冲
  • Channel 是 NIO中的一个接口 public interface Channel extends Closeable 、

  • 常用的channel类有:FileChannel,DatagramChannel,ServerSocketChannel,SocketChannel。【FileChannel用于文件数据的读写,DatagramChannel用于UDP数据的读写,ServerScoketChannel SocketChannel用于TCP数据的读写】

1 FileChannel 类

FileChannel 主要是用来对本地文件进行IO操作,常见的方法有:
在这里插入图片描述

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

【实例要求】
1、使用前面学习的ByteBuffer,FileChannel 将“hello,尚硅谷” 写入到file01.txt中
2、文件不存在则创建文件

在这里插入图片描述

public class NIOFileChannel01 {
    public static void main(String[] args) throws IOException {
        String str= "hello,尚硅谷";
        FileOutputStream fileOutputStream = new FileOutputStream("E://file01.txt");
        // channel的真是类型是 FileChannelImpl
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 将str扔到byteBuffer中
        byteBuffer.put(str.getBytes());
        // 对 byteBuffer 进行反转
        byteBuffer.flip();
        // 对于channel 来说是将 buffer中的数据写入到channel中
        channel.write(byteBuffer);
        // 关闭流
        fileOutputStream.close();
    }
}

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

使用前面学习到的ByteBuffer(缓冲)和 FileChannel(通道),将file01.txt中的数据读入到程序中,并显示在控制台上
在这里插入图片描述

public class NIOFileChannel02 {
    public static void main(String[] args) throws IOException {
        File file = new File("E://file01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        // channel的真是类型是 FileChannelImpl
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());
        channel.read(byteBuffer);
        System.out.println(new String(byteBuffer.array()));
        // 关闭流
        fileInputStream.close();
    }
}

3.5.4 应用实例3 - 使用一个buffer完成文件的读取写入

在这里插入图片描述

public class NIOFileChannel03 {

    public static void main(String[] args) throws IOException {
        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();
    }
}


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

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();
    }
}


3.5.6 Buffer和Channel的注意事项和细节

1)ByteBuffer支持类型化的put和get,put放入的是什么数据类型,get就需要使用相应的数据类型来取出,否则就可能有 BufferUnderflowException 异常
2)可以将一个普通Buffer转换成只读Buffer

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

在这里插入图片描述
3)NIO还提供了MapperedByteBuffer,可以让文件直接在内存中(堆外的内存)进行修改,而如何同步到文件由NIO来完成

4)前面我们讲的读写操作,都是通过一个Buffer完成的,NIO还支持通过多个Buffer(即Buffer数组)来完成读写操作,即Scattering 和 Gathering 【分散和聚合】

3.6 Selector(选择器)

3.6.1 Selector 基本介绍

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

【总结】多个Channel以事件的方式注册到同一个Selector,Selector可以检测到多个注册的channel上是否有事件发生
在这里插入图片描述

3.6.2 Selector的特点

在这里插入图片描述


3.6.3 Selector的常用方法

在这里插入图片描述


3.7 NIO 非阻塞编程原理分析

Selector,SelectionKey,ServerSocketChannel,SocketChannel之间的关系
在这里插入图片描述

  • 服务器ServerSocketChannel注册到selector
  • Selector进行监听,select()方法返回有事件发生的通道的个数
  • 当客户端连接时,Selector会监听到,通过ServerSocketChannel得到SocketChannel
  • 将SocketChannel注册到selector,并监听read事件,一个selector上可以注册多个Socketchannel
  • 当有read事件发生时,通过selector获取 SelectionKey,通过SelectionKey反向获取到channel,接收传来的message

3.8 NIO非阻塞网络编程demo

【案例要求】
编写一个NIO入门程序,实现服务器和客户端之间的数据简单通讯(非阻塞)

代码

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

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定一个端口,在服务器端进行监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        // serverSocketChannel 注册到selector, 关心事件为 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 循环等待客户端进行连接
        while (true) {
            if (selector.select(1000) == 0) {
               // System.out.println("服务器端等待了一秒,无连接");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // selector监听到 OP_ACCEPT事件,表示有新的客户端连接
                if (key.isAcceptable()) {
                    System.out.println("监听到客户端的注册事件,将客户端注册到server =======> ");
                    // 给该客户端生成一个socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    // 将socketChannel设置成非阻塞
                    socketChannel.configureBlocking(false);
                    // 将SocketChannel注册到selector,关注事件设置为 op_read
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                } else if (key.isReadable()) {
                    // 通过key反向获取到channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    channel.read(byteBuffer);
                    System.out.println("收到客户端传递过来的消息:" + new String(byteBuffer.array()));
                }
                iterator.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("因为连接需要时间,客户端不会阻塞,可以做其它工作..");
            }
        }

        while (true) {
            //...如果连接成功,就发送数据
            Scanner scanner = new Scanner(System.in);
            String in = scanner.nextLine();
            //Wraps a byte array into a buffer
            ByteBuffer buffer = ByteBuffer.wrap(in.getBytes());
            //发送数据,将 buffer 数据写入 channel
            socketChannel.write(buffer);
        }
    }
}

3.9 SelectionKey

1、SelectionKey 表示 Selector和网络通道之间的注册关系
在这里插入图片描述
selector.selectedKeys(): 表示当前有哪些注册到selector的通道发生了事件
selector.keys() : 表示当前有注册到selector的所有通道

2、SelectionKey 的相关方法
在这里插入图片描述

3.10 ServerSocketChannel 和 SocketChannel的相关api

1、ServerSocketChannel 在服务器端监听先的客户端 Socket连接

在这里插入图片描述

2、SocketChannel

网络IO通道,具体负责进行读写操作。NIO将buffer中的内容写入channel,或者将channel中的内容读到buffer
在这里插入图片描述

3.11 简单群聊系统的实现

package com.atgui.nio.qunliao;

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

public class GroupChatServer {


    private Selector selector;
    private ServerSocketChannel listenChannel;

    private static final int PORT = 6667;


    public GroupChatServer() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            // chat服务器线程一直循环进行监听
            while (true) {
                int count = selector.select(2000);
                if (count > 0) {
                    // 取出当前有事件的集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        // 监听到有客户端进行连接
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            // 将 socketChannel 也注册到 selector上
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + "上线");
                        }
                        // 发生了事件的通道是可读的状态
                        if (key.isReadable()) {
                            readData(key);
                        }
                        // 把当前的SelectionKey删除
                        iterator.remove();
                    }
                } else {
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    //
    private void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            // 由 SelectionKey 反向得到 channel
            channel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 返回读取到的长度
            int count = channel.read(byteBuffer);
            if (count > 0) {
                String message = new String(byteBuffer.array());
                System.out.println("from 客户端: " + message);
                // 向其他客户端转发消息
                broadMessage(message, channel);
            }
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "离线");
                // 用户离线了,取消注册、关闭通道
                key.cancel();
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    // 转发消息给所有通道,【注意】去掉自己
    private void broadMessage(String message, SocketChannel self) throws IOException {
        System.out.println("服务器开始转发消息");
        // 获取所有注册到selector的 SocketChannel,并排除自己
        for (SelectionKey key : selector.keys()) {
            SelectableChannel targetChannel = key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
                ((SocketChannel) targetChannel).write(byteBuffer);
            }
        }
    }

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

}


package com.atgui.nio.qunliao;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {

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

    //构造器, 完成初始化工作
    public GroupChatClient() throws IOException {

        selector = Selector.open();
        //连接服务器
        socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1", PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel 注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok...");

    }

    //向服务器发送消息
    public void sendInfo(String info) {

        info = username + " 说:" + info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取从服务器端回复的消息
    public void readInfo() {

        try {

            int readChannels = selector.select();
            if(readChannels > 0) {//有可以用的通道

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {

                    SelectionKey key = iterator.next();
                    if(key.isReadable()) {
                        //得到相关的通道
                       SocketChannel sc = (SocketChannel) key.channel();
                       //得到一个Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的selectionKey, 防止重复操作
            } else {
                //System.out.println("没有可以用的通道...");

            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

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

        //启动我们客户端
        GroupChatClient chatClient = new GroupChatClient();

        //启动一个线程, 每个3秒,读取从服务器发送数据
        new Thread() {
            public void run() {

                while (true) {
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(1000);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }


}

3.12 零拷贝

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

  • sendFile 优化
    在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值