Loading

Netty 实战 - 黑马 - NIO 基础

🍒 课程链接-黑马程序员Netty全套教程-bilibili

本文资料来源 黑马程序员Netty全套教程 课件

参考链接

一、课程介绍

1.1 课程内容

1.2 课程收获

二、NIO 基础

non-blocking io:非阻塞 IO

2.1 NIO 三大组件

2.1.1 Channel 与 Buffer

1)Java NIO 系统的核心在于:通道(Channel)和缓冲区(Buffer)。
  • Channel:双向的数据的传输通道(读写)。可以将 Channel 读入 Buffer,也可以将 Buffer 数据写入 Channel。

  • Buffer:内存缓冲区,用来暂存从 Channel 中读入的数据。向 Channel 中写数据时,也需要先将数据暂存到 Buffer 中。相当于应用程序与文件、网络之间的数据桥梁。

若需要使用 NIO 系统,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。简而言之,通道负责传输,缓冲区负责存储。

2)常见的 Channel 有以下四种

其中 FileChannel 主要用于文件传输,其余三种用于网络通信

  • FileChannel(文件传输)

  • DatagramChannel(UDP 网络编程时的数据传输通道)

  • SocketChannel(TCP 时数据的传输通道,客户端与服务器都可以使用)

  • ServerSocketChannel(TCP 时数据的传输通道,专用于服务器)

3)Buffer 有以下几种

其中使用较多的是 ByteBuffer,其他用的较少,了解即可。

  • ByteBuffer(以字节为单位缓冲数据,抽象类)
    • MappedByteBuffer
    • DirectByteBuffer
    • HeapByteBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer
  • CharBuffer

2.1.2 Selector 选择器

结合服务端代码设计理解 Selector 用途

1)多线程版设计(NIO 出现之前)

多线程版设计缺点:

  • 内存占用高
    • 每个线程都需要占用一定的内存,当连接较多时,会开辟大量线程,导致占用大量内存
  • 线程上下文切换成本高
    • 并不是线程数越多越好,线程数越多并不代表处理效率会越高。受 CPU 的核数限制。线程过多,不能执行的线程需要被保存线程执行状态,轮到线程运行时需要恢复状态,即上下文切换成本高。
  • 只适合连接数少的场景
    • 连接数过多,会导致创建很多线程,从而出现问题

默认情况下,windows 一个线程会占用 1M 内存。

2)线程池版设计

使用线程池,让线程池中的线程去处理连接

线程池版设计缺点:

  • 阻塞模式下,线程仅能处理一个连接
    • 线程池中的线程获取任务(task)后,只有当其执行完任务之后(断开连接后),才会去获取并执行下一个任务。若 socket 连接一直未断开,则其对应的线程无法处理其他 socket 连接。
  • 仅适合短连接场景
    • 短连接即建立连接发送请求并响应后就立即断开,使得线程池中的线程可以快速处理其他连接。
3)selector 版服务器设计

selector 的作用就是配合一个线程来管理多个 channel(fileChannel 因为是阻塞式的,所以无法使用 selector),获取这些 channel 上发生的事件,这些 channel 工作在非阻塞模式下,当一个 channel 中没有执行任务时,可以去执行其他 channel 中的任务。适合连接数多,但流量较少的场景(即每个 channel 并不是频繁操作的场景)。

调用 selector 的 select() 方法会阻塞线程,直到 channel 发生了就绪事件。这些事件就绪后,select 方法就会返回这些事件交给 thread 来处理。

2.2 ByteBuffer

2.2.1 ByteBuffer 基本使用

有一普通文本文件 data.txt,内容为

0123456789abcdef

使用 FileChannel 读取文件内容

package cn.itcast.nio.c2;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class TestByteBuffer {

    public static void main(String[] args) {
        // FileChannel
        // 1. 输入输出流, 2. RandomAccessFile
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            // 准备缓冲区,allocate 分配大小(单位字节)
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while(true) {
                // 从 channel 读取数据,向 buffer 写入
                int len = channel.read(buffer);
                log.debug("读取到的字节数 {}", len);
                if(len == -1) { // 没有内容了
                    break;
                }
                // 打印 buffer 的内容
                buffer.flip(); // 切换至读模式
                while(buffer.hasRemaining()) { // 是否还有剩余未读数据
                    byte b = buffer.get();
                    log.debug("实际字节 {}", (char) b);
                }
                buffer.clear(); // 切换为写模式
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
ByteBuffer 正确使用姿势
  1. 向 buffer 写入数据,例如调用 channel.read(buffer)

  2. 调用 flip() 切换至读模式

  3. 从 buffer 读取数据,例如调用 buffer.get()

  4. 调用 clear() 或 compact() 切换至写模式

  5. 重复 1~4 步骤

2.2.2 ByteBuffer 内部结构

ByteBuffer 有以下重要属性

  • capacity(容量)

  • position(读写指针,读到哪写到哪的一个索引下标)

  • limit(读写限制)

一开始

写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态:

flip 动作发生后,position 切换为读取位置,limit 切换为读取限制

读取 4 个字节后,状态

clear 动作发生后,状态

compact 方法,是把未读完的部分向前压缩,然后切换至写模式

2.2.3 ByteBuffer 常见方法

1) 分配空间

使用 allocate 方法为 ByteBuffer 分配空间,其它 buffer 类也有该方法

Bytebuffer buf = ByteBuffer.allocate(16);

分配后容量固定,不能动态调整。

package cn.itcast.nio.c2;

import java.nio.ByteBuffer;

public class TestByteBufferAllocate {
    public static void main(String[] args) {
        System.out.println(ByteBuffer.allocate(16).getClass());
        System.out.println(ByteBuffer.allocateDirect(16).getClass());
    }
}

输出

class java.nio.HeapByteBuffer - java 堆内存,读写效率较低,受到 GC 的影响
class java.nio.DirectByteBuffer - 直接内存,读写效率高(少一次拷贝),不会受 GC 影响。但其属于系统内存,需要调用操作系统函数,分配的效率低。使用不当,会造成内存泄露。

2) 向 buffer 写入数据

有两种办法

  • 调用 channel 的 read 方法(将数据写入 buffer)
int readBytes = channel.read(buf);
  • 调用 buffer 自己的 put 方法
buf.put((byte)127);
3) 从 buffer 读取数据

有两种办法

  • 调用 channel 的 write 方法
int writeBytes = channel.write(buf);
  • 调用 buffer 自己的 get 方法
byte b = buf.get();

get 方法会让 position 读指针向后走,如果想重复读取数据

  • 可以调用 rewind 方法将 position 重新置为 0
  • 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针
4) mark 和 reset

mark 是在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置。

rewind 和 flip 都会清除 mark 位置

5) 字符串与 ByteBuffer 互转
public class TestByteBufferString {
    public static void main(String[] args) {
        // 1. 字符串转为 ByteBuffer(仍然是写模式)
        ByteBuffer buffer1 = ByteBuffer.allocate(16);
        buffer1.put("hello".getBytes());
        debugAll(buffer1);

        // 2. Charset(自动切换到读模式)
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("hello");
        debugAll(buffer2);

        // 3. wrap(nio提供的工具类,自动切换到读模式)
        ByteBuffer buffer3 = ByteBuffer.wrap("hello".getBytes());
        debugAll(buffer3);

        // 4. ByteBuffer转为字符串
        String str1 = StandardCharsets.UTF_8.decode(buffer2).toString();
        System.out.println(str1);

        //对第一种方式,要先切换成读模式
        buffer1.flip();
        String str2 = StandardCharsets.UTF_8.decode(buffer1).toString();
        System.out.println(str2);

    }
}

⚠️ Buffer 是非线程安全的

2.2.4 Scattering Reads

分散读集中写:减少数据在 bytebuffer 之间的数据拷贝,减少数据的复制次数,从而提高效率。

分散读取,有一个文本文件 3parts.txt

onetwothree

使用如下方式读取,可以将数据填充至多个 buffer

try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
    FileChannel channel = file.getChannel();
    ByteBuffer a = ByteBuffer.allocate(3);
    ByteBuffer b = ByteBuffer.allocate(3);
    ByteBuffer c = ByteBuffer.allocate(5);
    channel.read(new ByteBuffer[]{a, b, c});
    a.flip(); //切换成读模式
    b.flip();
    c.flip();
    debugAll(a);
    debugAll(b);
    debugAll(c);
} catch (IOException e) {
    e.printStackTrace();
}

2.2.5 Gathering Writes

使用如下方式写入,可以将多个 buffer 的数据填充至 channel

1)方式一
public class TestGatheringWrites {
    public static void main(String[] args) {
        ByteBuffer b1 = StandardCharsets.UTF_8.encode("hello");
        ByteBuffer b2 = StandardCharsets.UTF_8.encode("world");
        ByteBuffer b3 = StandardCharsets.UTF_8.encode("你好"); //6字节

        try (FileChannel channel = new RandomAccessFile("words2.txt", "rw").getChannel()) {
            channel.write(new ByteBuffer[]{b1, b2, b3});
        } catch (IOException e) {
        }
    }
}
2)方式二

初始文件内容:onetwothree

运行后文件内容:onetwothreefourfive

try (RandomAccessFile file = new RandomAccessFile("helloword/3parts.txt", "rw")) {
    FileChannel channel = file.getChannel();
    ByteBuffer d = ByteBuffer.allocate(4);
    ByteBuffer e = ByteBuffer.allocate(4);
    //通过 position(newPosition) 来设置
    //跳过 onetwothree,从 文件尾 开始写入
    channel.position(11); 

    d.put(new byte[]{'f', 'o', 'u', 'r'});
    e.put(new byte[]{'f', 'i', 'v', 'e'});
    d.flip();
    e.flip();
    channel.write(new ByteBuffer[]{d, e});
} catch (IOException e) {
    e.printStackTrace();
}

2.2.6 黏包半包-初级处理

1)问题描述

网络上有多条数据发送给服务端,数据之间使用 \n 进行分隔。但由于某种原因这些数据在接收时,被进行了重新组合,例如原始数据有 3 条为

  • Hello,world\n
  • I'm zhangsan\n
  • How are you?\n

变成了下面的两个 byteBuffer (黏包,半包)

  • Hello,world\nI'm zhangsan\nHo
  • w are you?\n

现在要求你编写程序,将错乱的数据恢复成原始的按 \n 分隔的数据

2)问题分析

黏包产生原因:为了效率,逐条发送信息效率低,若干条信息一起发送,效率高。

半包产生原因:由于服务器缓冲区大小限制。

3)实现
  • 方式一
public class TestByteBufferExam {
    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(32);
        //模拟网络传输
        source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
        split(source);
        source.put("w are you?\n".getBytes());
        split(source);
    }

    private static void split(ByteBuffer source) {
        source.flip(); //读模式
        for (int i = 0; i < source.limit(); i++) {
            // 找到一条完整消息
            if (source.get(i) == '\n') {
                int length = i - source.position() + 1;
                // 把这条完整消息存入新的 ByteBuffer
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从 source 读,向 target 写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        source.compact(); //写模式
    }
}
  • 方式二
public static void main(String[] args) {
    ByteBuffer source = ByteBuffer.allocate(32);
    //                     11            24
    source.put("Hello,world\nI'm zhangsan\nHo".getBytes());
    split(source);

    source.put("w are you?\nhaha!\n".getBytes());
    split(source);
}

private static void split(ByteBuffer source) {
    source.flip(); //首先切换为读模式
    int oldLimit = source.limit();
    //遍历 byteBuffer
    for (int i = 0; i < oldLimit; i++) {
        if (source.get(i) == '\n') {
            System.out.println(i);
            ByteBuffer target = ByteBuffer.allocate(i + 1 - source.position());
            // 0 ~ limit
            source.limit(i + 1);
            target.put(source); // 从source 读,向 target 写
            source.limit(oldLimit);
        }
    }
    source.compact(); //切换为写模式,不能用clear。未读消息需要保留
}

2.3 文件编程

2.3.1 FileChannel

⚠️ FileChannel 工作模式:FileChannel 只能工作在阻塞模式下,不能与 Selector 一起用。

1) 获取

不能直接打开 FileChannel,必须通过 FileInputStream、FileOutputStream 或者 RandomAccessFile 来获取 FileChannel,它们都有 getChannel 方法。

  • 通过 FileInputStream 获取的 channel 只能读
  • 通过 FileOutputStream 获取的 channel 只能写
  • 通过 RandomAccessFile 是否能读写,根据构造 RandomAccessFile 时的读写模式决定(传入 r\w\rw 等参数)
2) 读取

从 channel 读取数据填充 ByteBuffer,返回值表示读到了多少字节,-1 表示到达了文件的末尾。

int readBytes = channel.read(buffer);
3) 写入

写入的正确姿势如下, SocketChannel 必须这样做,FileChannel 可以不这样做。

ByteBuffer buffer = ...;
buffer.put(...); // 存入数据
buffer.flip();   // 切换读模式

while(buffer.hasRemaining()) {
    channel.write(buffer);
}
  • 在 while 中调用 channel.write 是因为 write 方法并不能保证一次将 buffer 中的内容全部写入 channel
4) 关闭

channel 必须关闭! 调用 FileInputStream、FileOutputStream 或者 RandomAccessFile 的 close 方法会间接地调用 channel 的 close 方法。

5) 位置

获取当前位置

long pos = channel.position();

设置当前位置

long newPos = ...;
channel.position(newPos);
  • 设置当前位置时,如果设置为文件的末尾

    • 这时读取会返回 -1

    • 这时写入,会追加内容,但要注意如果 position 超过了文件末尾,再写入时在新内容和原末尾之间会有空洞(00)

6) 大小

使用 size 方法获取文件的大小

7) 强制写入

操作系统出于性能的考虑,会将数据缓存,不是立刻写入磁盘。只有当 Channal 真正的关闭时,才会同步到磁盘中。可以调用 force(true) 方法将文件内容和元数据(文件的权限等信息)立刻写入磁盘。

2.3.2 transferTo 传输数据

transferTo :从一个 Channel 将数据传输到另一个 Channel。

1) 两个 Channel 传输数据
String FROM = "helloword/data.txt";
String TO = "helloword/to.txt";
long start = System.nanoTime();
try (FileChannel from = new FileInputStream(FROM).getChannel();
     FileChannel to = new FileOutputStream(TO).getChannel();
    ) {
    //效率高,transferTo 底层会利用操作系统的零拷贝进行优化
    from.transferTo(0, from.size(), to);
} catch (IOException e) {
    e.printStackTrace();
}
long end = System.nanoTime();
System.out.println("transferTo 用时:" + (end - start) / 1000_000.0);
2) 超过 2g 大小的文件传输
  • transferTo 传输上限 2g
public class TestFileChannelTransferTo {
    public static void main(String[] args) {
        try (
                FileChannel from = new FileInputStream("data.txt").getChannel();
                FileChannel to = new FileOutputStream("to.txt").getChannel();
        ) {
            // 效率高,底层会利用操作系统的零拷贝进行优化
            long size = from.size();
            // left 变量代表还剩余多少字节
            for (long left = size; left > 0; ) {
                System.out.println("position:" + (size - left) + " left:" + left);
                //transferTo 返回实际传输的字节数
                left -= from.transferTo((size - left), left, to);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.3.3 Path

jdk7 引入了 Path 和 Paths 类

  • Path 用来表示文件路径

  • Paths 是工具类,用来获取 Path 实例

Path source = Paths.get("1.txt"); // 相对路径 使用 user.dir 环境变量来定位 1.txt

Path source = Paths.get("d:\\1.txt"); // 绝对路径 代表了  d:\1.txt

Path source = Paths.get("d:/1.txt"); // 绝对路径 同样代表了  d:\1.txt

// '/' 不用转义  '\\'需要转义

//拼接结果代表最终路径
Path projects = Paths.get("d:\\data", "projects"); // 代表了  d:\data\projects

其中,

  • . 代表了当前路径

  • .. 代表了上一级路径

如目录结构如下:

d:
    |- data
        |- projects
            |- a
            |- b

代码

Path path = Paths.get("d:\\data\\projects\\a\\..\\b");
System.out.println(path);
System.out.println(path.normalize()); // 正常化路径

输出

d:\data\projects\a\..\b
d:\data\projects\b

2.3.4 Files

1) 检查文件是否存在
Path path = Paths.get("helloword/data.txt");
System.out.println(Files.exists(path));
2) 创建一级目录
Path path = Paths.get("helloword/d1");
Files.createDirectory(path);
  • 如果目录已存在,会抛异常 FileAlreadyExistsException
  • 不能一次创建多级目录,否则会抛异常 NoSuchFileException
3) 创建多级目录用
Path path = Paths.get("helloword/d1/d2");
Files.createDirectories(path);
4) 拷贝文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/target.txt");

Files.copy(source, target);
  • 如果文件已存在,会抛异常 FileAlreadyExistsException

如果希望用 source 覆盖掉 target,需要用 StandardCopyOption 来控制

Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

与 transferTo 实现原理不一样,但是性能差不多

5) 移动文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/data.txt");

Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
  • StandardCopyOption.ATOMIC_MOVE 保证文件移动的原子性
6) 删除文件
Path target = Paths.get("helloword/target.txt");

Files.delete(target);
  • 如果文件不存在,会抛异常 NoSuchFileException
7) 删除目录
Path target = Paths.get("helloword/d1");

Files.delete(target);
  • 如果目录还有内容,会抛异常 DirectoryNotEmptyException
8) 遍历目录文件-walkFileTree
public static void main(String[] args) throws IOException {
    Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
    AtomicInteger dirCount = new AtomicInteger();
    AtomicInteger fileCount = new AtomicInteger();
    Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) 
            throws IOException {
            System.out.println(dir);
            dirCount.incrementAndGet();
            return super.preVisitDirectory(dir, attrs);
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
            throws IOException {
            System.out.println(file);
            fileCount.incrementAndGet();
            return super.visitFile(file, attrs);
        }
    });
    System.out.println(dirCount); // 133
    System.out.println(fileCount); // 1479
}
  • 使用的是访问者模式

  • 重写时,return 不要修改!

  • preVisitDirectory 进入文件夹之前

  • postVisitDirectory 从文件夹出来之后

  • visitFile 遍历文件

  • 使用 AtomicInteger,不能使用 int 变量。

9) 统计 jar 的数目
Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
AtomicInteger fileCount = new AtomicInteger();
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
        throws IOException {
        if (file.toFile().getName().endsWith(".jar")) {
            fileCount.incrementAndGet();
        }
        return super.visitFile(file, attrs);
    }
});
System.out.println(fileCount); // 724
  • file.toString().endsWith(".jar")
10) 删除多级目录
Path path = Paths.get("d:\\a");
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
        throws IOException {
        Files.delete(file);
        return super.visitFile(file, attrs);
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) 
        throws IOException {
        Files.delete(dir);
        return super.postVisitDirectory(dir, exc);
    }
});

⚠️ 删除很危险(不走回收站) ,确保要递归删除的文件夹没有重要内容

11) 拷贝多级目录
  • walk 函数返回 stream 类型
long start = System.currentTimeMillis();
String source = "D:\\Snipaste-1.16.2-x64";
String target = "D:\\Snipaste-1.16.2-x64aaa";

Files.walk(Paths.get(source)).forEach(path -> {
    try {
        String targetName = path.toString().replace(source, target);
        // 是目录
        if (Files.isDirectory(path)) {
            Files.createDirectory(Paths.get(targetName));
        }
        // 是普通文件
        else if (Files.isRegularFile(path)) {
            Files.copy(path, Paths.get(targetName));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
});
long end = System.currentTimeMillis();
System.out.println(end - start);

2.4 网络编程

2.4.1 非阻塞 vs 阻塞

1) 阻塞
  • 阻塞模式下,相关方法都会导致线程暂停
    • ServerSocketChannel.accept 会在没有连接建立时让线程暂停
    • SocketChannel.read 会在没有数据可读时让线程暂停
    • 阻塞的表现其实就是线程暂停,暂停期间不会占用 cpu,但线程相当于闲置
  • 单线程下,阻塞方法之间相互影响,几乎不能正常工作,需要多线程支持
  • 但多线程下,有新的问题,体现在以下方面
    • 32 位 jvm 一个线程 320k,64 位 jvm 一个线程 1024k,如果连接数过多,必然导致 OOM,并且线程太多,反而会因为频繁上下文切换导致性能降低
    • 可以采用线程池技术来减少线程数和线程上下文切换,但治标不治本,如果有很多连接建立,但长时间 inactive,会阻塞线程池中所有线程,因此不适合长连接,只适合短连接

【服务器端】

// 使用 nio 来理解阻塞模式, 单线程
// 0. ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(16);
// 1. 创建了服务器
ServerSocketChannel ssc = ServerSocketChannel.open();

// 2. 绑定监听端口
ssc.bind(new InetSocketAddress(8080));

// 3. 连接集合
List<SocketChannel> channels = new ArrayList<>();
while (true) {
    // 4. accept 建立与客户端连接, SocketChannel 用来与客户端之间通信
    log.debug("connecting...");
    SocketChannel sc = ssc.accept(); // 阻塞方法,当没有客户端请求连接时,线程停止运行
    log.debug("connected... {}", sc);
    channels.add(sc);
    for (SocketChannel channel : channels) {
        // 5. 接收客户端发送的数据
        log.debug("before read... {}", channel);
        channel.read(buffer); // 阻塞方法,当没有收到客户端数据时,线程停止运行
        buffer.flip();
        debugRead(buffer); //工具类(见文章末尾)中,获取可读字节并打印
        buffer.clear();
        log.debug("after read...{}", channel);
    }
}

【客户端】

SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost", 8080));
System.out.println("waiting...");

上述方法问题:没有新连接时,原连接继续发送数据不会立即被处理。List 中未使用的 channel 没有被移除,会不停累计。

2) 非阻塞
  • 非阻塞模式下,相关方法都会不会让线程暂停
    • 在 ServerSocketChannel.accept 在没有连接建立时,会返回 null,继续运行
    • SocketChannel.read 在没有数据可读时,会返回 0,但线程不必阻塞,可以去执行其它 SocketChannel 的 read 或是去执行 ServerSocketChannel.accept
    • 写数据时,线程只是等待数据写入 Channel 即可,无需等 Channel 通过网络把数据发送出去
  • 但非阻塞模式下,即使没有连接建立,和可读数据,线程仍然在不断运行,白白浪费了 cpu
  • 数据复制过程中,线程实际还是阻塞的(AIO 改进的地方)

【服务器端】

// 使用 nio 来理解非阻塞模式, 单线程
// 0. ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(16);
// 1. 创建了服务器
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false); // 非阻塞模式🍒
// 2. 绑定监听端口
ssc.bind(new InetSocketAddress(8080));
// 3. 连接集合
List<SocketChannel> channels = new ArrayList<>();
while (true) {
    // 4. accept 建立与客户端连接, SocketChannel 用来与客户端之间通信
    SocketChannel sc = ssc.accept(); // 非阻塞,线程还会继续运行,如果没有连接建立,但sc是null
    if (sc != null) {
        log.debug("connected... {}", sc);
        sc.configureBlocking(false); // 非阻塞模式🍒
        channels.add(sc);
    }
    for (SocketChannel channel : channels) {
        // 5. 接收客户端发送的数据
        int read = channel.read(buffer);// 非阻塞,线程仍然会继续运行,如果没有读到数据,read 返回 0
        if (read > 0) {
            buffer.flip();
            debugRead(buffer);
            buffer.clear();
            log.debug("after read...{}", channel);
        }
    }
}

【客户端】

代码不变

即使没有事件发生,也会一直循环,造成 CPU 浪费! List 中未使用的 channel 没有被移除,会不停累计。

3) 多路复用

单线程可以配合 Selector 完成对多个 Channel 可读写事件的监控,这称之为多路复用。

  • 多路复用仅针对网络 IO、普通文件 IO 没法利用多路复用
  • 如果不用 Selector 的非阻塞模式,线程大部分时间都在做无用功,而 Selector 能够保证
    • 有可连接事件时才去连接
    • 有可读事件才去读取
    • 有可写事件才去写入:限于网络传输能力,Channel 未必时时可写,一旦 Channel 可写,会触发 Selector 的可写事件

2.4.2 Selector

使用 Selector 的好处

  • 一个线程配合 selector 就可以监控多个 channel 的事件,事件发生线程才去处理。避免非阻塞模式下所做无用功。没有事件发生则阻塞,不占用 CPU。
  • 让这个线程能够被充分利用
  • 节约了线程的数量
  • 减少了线程上下文切换
1)创建
Selector selector = Selector.open(); //没有使用 new
2)绑定 Channel 事件(也称之为注册事件)

绑定的事件 selector 才会关心

ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
SelectionKey key = ssc.register(selector, 绑定事件);
  • channel 必须工作在非阻塞模式

  • FileChannel 没有非阻塞模式,因此不能配合 selector 一起使用

  • 绑定的事件类型可以有

    • connect - 客户端连接成功时触发
    • accept - 服务器端成功接受连接时触发
    • read - 数据可读入时触发,有因为接收能力弱,数据暂不能读入的情况
    • write - 数据可写出时触发,有因为发送能力弱,数据暂不能写出的情况
  • SelectionKey 是返回值,事件发生后,通过它可以知道是什么事件和哪个channel的发生该事件

3)监听 Channel 事件

可以通过下面三种方法来监听是否有事件发生,方法的返回值代表有多少 channel 发生了事件

  • 方法 1,阻塞直到绑定事件发生
int count = selector.select();
  • 方法 2,阻塞直到绑定事件发生,或是超时(时间单位为 ms)
int count = selector.select(long timeout);
  • 方法3,不会阻塞,也就是不管有没有事件,立刻返回,自己根据返回值检查是否有事件
int count = selector.selectNow();
💡 select 何时不阻塞
  • 事件发生时
    • 客户端发起连接请求,会触发 accept 事件。
    • 客户端发送数据过来以及客户端正常、异常关闭时,都会触发 read 事件,另外如果发送的数据大于 buffer 缓冲区,会触发多次读取事件。
    • channel 可写,会触发 write 事件。
    • 在 linux 下 nio bug 发生时。
  • 调用 selector.wakeup():唤醒阻塞在 selector 上的线程。
  • 调用 selector.close()
  • selector 所在线程 interrupt。

2.4.3 处理 accept 事件

【服务器端】

package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class Server {

    public static void main(String[] args) throws IOException {
        // 1. 创建 selector, 管理多个 channel
        Selector selector = Selector.open(); //🍒
        ServerSocketChannel ssc = ServerSocketChannel.open(); //🍅
        ssc.configureBlocking(false); //🍅
        // 2. 建立 selector 和 channel 的联系(注册)
        // SelectionKey 就是将来事件发生后,通过它可以知道事件和哪个channel的事件
        // 此处第二个参数 0 表示不关注任何事件
        SelectionKey sscKey = ssc.register(selector, 0, null); //🍒
        // interestOps设置关注事件,此处 key 只关注 accept 事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("sscKey:{}", sscKey);
        ssc.bind(new InetSocketAddress(8080)); //🍅
        while (true) {
            // 3. select 方法, 没有事件发生,线程阻塞(不占用CPU),有事件,线程才会恢复运行
            selector.select(); //🍒
            // 4. 处理事件, selectedKeys 内部包含了所有发生的事件
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); // accept, read //🍒
            while (iter.hasNext()) {
                SelectionKey key = iter.next();//🍒
                // 处理key 时,要从 selectedKeys 集合中删除,否则下次处理就会有问题
                iter.remove();//🍒🍒🍒
                log.debug("key: {}", key);
                // 5. 区分事件类型
                if (key.isAcceptable()) { // 如果是 accept(可连接事件)
                    //获取发生事件的 channel
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel(); //🍒
                    SocketChannel sc = channel.accept(); //🍅
                    sc.configureBlocking(false); //🍅

                    SelectionKey scKey = sc.register(selector, 0, null); //🍒
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}", sc);
                    log.debug("scKey:{}", scKey);
                } else if (key.isReadable()) { // 如果是 read
                    key.cancel(); //暂时先不处理
                }
            }
        }
    }
}

💡 知识点

  • 事件发生后要么处理,要么取消,不能置之不理。

    • select 在有未处理事件时,不会阻塞,如果发生的事件一直不处理,则下一次会继续注册到SelectionKey。
    • 处理:channel.accept()、channel.read(buffer)、key.cancel()
    • 所以,事件发生后要么处理,要么取消,不能置之不理。否则下次该事件仍会触发,这是因为 nio 底层使用的是水平触发,会造成一直循环。
  • 处理 key 时,要从 selectedKeys 集合中将其删除,否则下次处理就会有问题:iter.remove()

    • selectedKeys 内部包含了所有发生的事件
    • selector 会在发生事件后向 selectedKeys 集合中添加事件,在处理后会将其标记为已处理,但是并不会删除
    • 已处理的 key 仍然存在 selectedKeys 集合中,在下一次调用 accpet 或 read 时,会返回空,向下执行其他语句报错。
    • 如:第一次触发了 ssckey 上的 accept 事件,没有移除 ssckey。第二次触发了 sckey 上的 read 事件,但这时 selectedKeys 中还有上次的 ssckey ,在处理时因为没有真正的 serverSocket 连上了,就会导致空指针异常。

2.4.4 处理 read 事件

客户端正常、异常关闭,均会触发的 read 事件。

... ...
} else if (key.isReadable()) { // 如果是 read
    try {
        SocketChannel channel = (SocketChannel) key.channel(); // 拿到触发事件的channel
        ByteBuffer buffer = ByteBuffer.allocate(4);
        int read = channel.read(buffer); // 如果是正常断开,read 的方法的返回值是 -1
        if(read == -1) {
            key.cancel(); //客户端断开,将 key 取消
        } else {
            buffer.flip();
            System.out.println(Charset.defaultCharset().decode(buffer));
        }
    } catch (IOException e) {
        e.printStackTrace();
        key.cancel();  // 客户端异常断开,因此需要将 key 取消(从 selector 的 keys 集合中真正删除 key)
    }

上述代码存在问题:没有正确处理消息的边界。如当客户端使用 defaultCharset 编码发送【中国】,每个汉字由三个字节构成,而服务器一次可以处理四字节,【国】被分两次读取,显示乱码。

处理消息的边界

思路一:客户端与服务端约定一个固定消息长度,数据包大小一样,服务器按预定长度读取,缺点是浪费带宽。

  • 客户端数据不足,则填充至约定长度。

思路二:发送消息时,使用分隔符分割消息。服务端按分隔符拆分,缺点是服务端要一个一个对比数据中是否含有分割符,效率低。

思路三:每一条消息的开始先存储该条消息的长度,然后再接着存储消息数据。将上述分两步发送给服务器。服务器根据消息的长度信息(整型数据),创建对应大小的 ByteBuffer,然后读取消息。这个是最常用的方法,http 协议就是采用这种方法

  • 思路三有一个专用的名字:TLV 格式,即 Type 类型、Length 长度、Value 数据,类型和长度已知的情况下,就可以方便获取消息大小,分配合适的 buffer,缺点是 buffer 需要提前分配,如果内容过大,则影响 server 吞吐量
    • Http 1.1 是 TLV 格式
    • Http 2.0 是 LTV 格式
分隔符分割消息代码实现

【客户端】

public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("localhost", 8080));
        SocketAddress address = sc.getLocalAddress();
        sc.write(Charset.defaultCharset().encode("hello\nworld\n"));
        System.in.read();
    }
}

【服务端】

private static void split(ByteBuffer source) {
    source.flip();
    for (int i = 0; i < source.limit(); i++) {
        // 找到一条完整消息
        if (source.get(i) == '\n') {
            int length = i + 1 - source.position();
            // 把这条完整消息存入新的 ByteBuffer
            ByteBuffer target = ByteBuffer.allocate(length);
            // 从 source 读,向 target 写
            for (int j = 0; j < length; j++) {
                target.put(source.get());
            }
            debugAll(target);
        }
    }
    source.compact();
}

... ...
} else if (key.isReadable()) { // 如果是 read
    try {
        SocketChannel channel = (SocketChannel) key.channel(); // 拿到触发事件的channel
        ByteBuffer buffer = ByteBuffer.allocate(16);
        int read = channel.read(buffer); // 如果是正常断开,read 的方法的返回值是 -1
        if(read == -1) {
            key.cancel(); //客户端断开,将 key 取消
        } else {
            split(buffer); //🍒
        }
    } catch (IOException e) {
        e.printStackTrace();
        key.cancel();  // 客户端异常断开,因此需要将 key 取消(从 selector 的 keys 集合中真正删除 key)
    }
}
单条消息超出 ByteBuffer 容量

【场景描述】

客户端发送消息超出服务端 ByteBuffer 容量

//服务端容量 16字节
ByteBuffer buffer = ByteBuffer.allocate(16);
//客户端发送消息 >16字节
sc.write(Charset.defaultCharset().encode("0123456789abcdef3333\n"));

服务端的 read 函数会被触发 2 次,第一次 0123456789abcdef 存入 ByteBuffer,但由于 split 函数没有找到 /n 字符,所以没有做任何处理。第二次 3333\n 存入 ByteBuffer,split 函数找到 /n 字符,将 3333 输出。

【解决方案】

第一次存入没有发现消息结束,则对 ByteBuffer1 进行扩容新建一个2倍大的 ByteBuffer2,将 ByteBuffer1 拷贝至 ByteBuffer2,未被读取数据第二次触发 read 时,向 ByteBuffer2 写入。因此,要求 ByteBuffer2 能同时被 2 次 read 读取到,不能是 else-if 的局部变量。让每个 SocketChannel 有自己的 Buffer。

【服务端代码-附件与扩容】

public class Server {

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            // 找到一条完整消息
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                // 把这条完整消息存入新的 ByteBuffer
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从 source 读,向 target 写
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                debugAll(target);
            }
        }
        //如果 source 中没有获取到 `/n`,则说明没有执行读取数据,
        //此时,position=16,limit=16
        source.compact(); //🍒 让position变成剩余未读字节数
    }

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

        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);

        SelectionKey sscKey = ssc.register(selector, 0, null);

        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("sscKey:{}", sscKey);
        ssc.bind(new InetSocketAddress(8080));

        while (true) {
            selector.select();
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();

                if (key.isAcceptable()) { // 如果是 accept(可连接事件)

                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);

                    ByteBuffer buffer = ByteBuffer.allocate(16); //🍒
                    //把 buffer 作为附件关联到 scKey
                    SelectionKey scKey = sc.register(selector, 0, buffer); //🍒

                    scKey.interestOps(SelectionKey.OP_READ);

                    } else if (key.isReadable()) { // 如果是 read
                        try {
                            SocketChannel channel = (SocketChannel) key.channel();
                            //获取 SelectionKey 上关联的附件
                            ByteBuffer buffer = (ByteBuffer) key.attachment(); //🍒
                            int read = channel.read(buffer);
                            if(read == -1) {
                                key.cancel(); //客户端断开,将 key 取消
                            } else {
                                System.out.println(Charset.defaultCharset().decode(buffer));
                                split(buffer);
                                //🍒🍒🍒
                                if(buffer.position()==buffer.limit()){
                                    //说明buffer满了,需要扩容
                                    ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity()*2);
                                    buffer.flip();
                                    newBuffer.put(buffer);
                                    //用 newBuffer 替换调原有的 buffer
                                    key.attach(newBuffer);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            key.cancel();  // 客户端异常断开,因此需要将 key 取消(从 selector 的 keys 集合中真正删除 key)
                        }
                }
            }
        }
    }
}
ByteBuffer 大小分配
  • 每个 channel 都需要记录可能被切分的消息,因为 ByteBuffer 不能被多个 channel 共同使用,因此需要为每个 channel 维护一个独立的 ByteBuffer。
  • ByteBuffer 不能太大,比如一个 ByteBuffer 1Mb 的话,要支持百万连接就要 1Tb 内存,因此需要设计大小可变的 ByteBuffer。
    • 一种思路是首先分配一个较小的 buffer,例如 4k,如果发现数据不够,再分配 8k 的 buffer,将 4k buffer 内容拷贝至 8k buffer,优点是消息连续容易处理,缺点是数据拷贝耗费性能,参考实现 http://tutorials.jenkov.com/java-performance/resizable-array.html
    • 另一种思路是用多个数组组成 buffer,一个数组不够,把多出来的内容写入新的数组,与前面的区别是消息存储不连续解析复杂,优点是避免了拷贝引起的性能损耗

2.4.5 处理 write 事件

服务器写入过多内容

服务器一次向客户端写入过多内容

【客户端】

public class WriteClient {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("localhost", 8080));

        // 3. 接收数据
        int count = 0;
        while (true) {
            ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
            count += sc.read(buffer);
            System.out.println(count);
            buffer.clear();
        }
    }
}

【分析】

由于服务器上写缓存区(操作系统)大小固定,数据会被分批发送

返回0表示写不了,while 循环会让其一直不断尝试--> 阻塞在该处!

希望当发送缓冲区满写不了内容时,暂时去处理别的操作,如写缓冲区满了可以去读数据。等写缓冲区空了,触发一个写事件,然后再去写,不要反复的去尝试。

处理一次性写不完的可写事件
public class WriteServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            selector.select();
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, 0, null);
                    sckey.interestOps(SelectionKey.OP_READ);
                    // 1. 向客户端发送大量数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());

                    // 2. 返回值代表实际写入的字节数
                    int write = sc.write(buffer);
                    System.out.println(write);

                    // 3. 判断是否有剩余内容
                    if (buffer.hasRemaining()) {
                        // 4. 关注可写事件   1                     4
                        sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);
//                        sckey.interestOps(sckey.interestOps() | SelectionKey.OP_WRITE);
                        // 5. 把未写完的数据挂到 sckey 上
                        sckey.attach(buffer);
                    }
                } else if (key.isWritable()) {
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    // 6. 清理操作
                    if (!buffer.hasRemaining()) {
                        key.attach(null); // 需要清除buffer,没有其它引用buffer,会被垃圾回收
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);//不需关注可写事件
                    }
                }
            }
        }
    }
}

2.4.6 利用多线程优化

该部分内容参考于kfcuj-04 多线程模式下selector的使用以及IO模型概念的区分

【多线程优化原因】

单线程配合 selector 选择器虽然能够管理多个 channel 的事件,但仍存在以下缺点:

  • 多核 cpu 被白白浪费

  • 某个事件耗费时间比较长会影响其他事件的处理。

单线程处理多个事件适合每个事件的处理时间比较短的情况。

补充:Redis 采用单线程处理,如果某个操作时间较长,会影响其他操作,所以使用 Redis 时,选择的单个操作时间复杂度不能太高。

【多线程架构模型】

分成两个模块:boss 模块和 worker 模块(通常是一个 boss 线程配合多个 work 线程):

  • boss 模块(只负责接待):多线程机制(每个线程都有一个 selector),专门用于处理客户端的连接事件

  • worker 模块(只负责读写):多个 worker,每个 worker 实际上是一个线程配合一个selector,worker 专门负责数据的读写操作

通常线程的数目与 CPU 的核心数目是一致的。

多线程 selector - 无法获取可读事件
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
@Slf4j
public class Server7 {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss"); //设置线程名字
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open(); //专门用于处理accept event
        SelectionKey bossKey = ssc.register(boss,0,null);  //将channel与selector关联起来
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));

        // 1 创建固定数量的worker并初始化
        Worker worker = new Worker("worker-0");
        worker.register();
        while(true){
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while(iter.hasNext()){
                SelectionKey key = iter.next();
                iter.remove();;
                if(key.isAcceptable()){
                    log.debug("accept event happen!");
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("before register...{}",sc.getRemoteAddress());
                    // 2. 关联selector
                    sc.register(worker.selector,SelectionKey.OP_READ,null);
                    log.debug("after register...{}",sc.getRemoteAddress());
                }
            }
        }
    }
    // 只有内部类能够定义为static
    // 为了在 main 函数中使用,定义为static类
    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name; //work对应的线程名字
        private volatile boolean start = false;

        public Worker(String name){this.name = name;}
        // 初始化线程和selector
        public void register() throws IOException {
            if(!start){   // 利用 start 保证这段代码只会被执行一次。
                selector = Selector.open();   // open返回:SelectorProvider.provider().openSelector()
                thread = new Thread( this,name);
                thread.start();
                start = true;
            }

        }
        @Override
        public void run() {
            while(true){
                try{
                    log.debug("begin select!");
                    selector.select();
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while(iter.hasNext()){
                        SelectionKey key = iter.next();
                        iter.remove();
                        /*这里实际读写需要考虑消息边界,写的数据规模过大的问题,以及连接的正常/异常关闭问题详见单线程版本设计*/
                        if(key.isReadable()){
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            channel.read(buffer);
                            buffer.flip();
                            printBytebuffer(buffer);
                        }
                    }

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

        }
    }
    static void printBytebuffer(ByteBuffer tmp){      // 注意:传入的bytebuffer必须时写模式
        System.out.println(StandardCharsets.UTF_8.decode(tmp).toString());
    }
}

客户端建立连接并发送数据后的执行结果

14:44:05.969 [worker-0] DEBUG Server.Server7 - begin select!
14:44:14.910 [boss] DEBUG Server.Server7 - accept event happen!
14:44:14.911 [boss] DEBUG Server.Server7 - before register.../127.0.0.1:14363   // 无法获取可读事件

【问题】服务端的 boss 模块的 selector 能够处理 accept 事件,但是 work 模块去无法获取可读事件。

【原因分析】主要原因在于 worker 线程执行了 select 方法后会阻塞,等待事件发生,此时由于 work 阻塞于 select,主线程 sc.register(worker.selector,SelectionKey.OP_READ,null); 中 register 方法就无法生效。造成 selector 没有监控读写事件(线程的异步性引发问题)。

代码段1:主线程让 worker 的 selector 监控读写通道(主线程执行该方法!!!)

sc.register(worker.selector,SelectionKey.OP_READ,null);

代码段2:worker 线程的 run 方法内部 select 方法(worker0 线程执方法!!)

public void run() {
    while(true){
      try{
        selector.select();
利用任务队列与wakeup解决可读事件无法获取的问题

【解决思路】让 boss 线程执行注册任务(Worker 中的代码),通过任务队列的方法将任务对象传递给 worker 线程

【服务端代码】

import lombok.extern.slf4j.Slf4j;
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;
import java.util.concurrent.ConcurrentLinkedQueue;
@Slf4j
public class Server8 {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss,0,null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        Worker worker = new Worker("worker-0"); //🍒 创建 work 线程
        while(true){
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while(iter.hasNext()){
                SelectionKey key = iter.next();
                iter.remove();
                if(key.isAcceptable()){
                    log.debug("accept event happen!");
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    worker.register(sc);     //🍒  首次调用启动线程并注册,后去调用仅仅注册
                }
            }
        }
    }
    // 只有内部类能够定义为static
    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>(); //🍒

        public Worker(String name){this.name = name;}
        // 初始化线程和selector
        /*======改进1:【boss所在线程】在accept事件发生后调用该方法,将Runable对象放入消息队列 =======*/
        public void register(SocketChannel sc) throws IOException {
            if(!start){   // 利用start确保worker线程只有一个
                selector = Selector.open();   
                thread = new Thread(this, name);
                thread.start();  //🍒 此时run函数阻塞在selector.select();
                start = true;
            }
            // 向队列中添加注册任务(runable任务),当【worker线程】运行时从这个队列获取任务并执行
            // 确保channel的注册在select之前。
            queue.add(()->{
                try{
                  sc.register(selector,SelectionKey.OP_READ,null); //🍒
                  selector.selectNow();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            selector.wakeup();     // 这个方法调用让select方法立刻返回一次,确保注册的完成
            log.debug("Wake up for to register new read/write channel for the selector!");
        }
        @Override
        public void run() {
            while(true){
                try{
                    selector.select();
                    /*======改进1:将Runable对象从消息队列取出完成注册======*/
                    Runnable task = queue.poll();
                    if(task != null){
                        task.run();  // 执行了sc.register(selector,SelectionKey.OP_READ,null)
                        log.debug("Register successfully!");
                    }
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while(iter.hasNext()){
                        SelectionKey key = iter.next();
                        /*这里实际读写需要考虑消息边界,写的数据规模过大的问题,详见单线程版本设计*/
                        /*对于可读事件,需要考虑三种情况:
                        * 1)正常的可读事件  2)客户端异常的关闭(需要处理异常) 3)客户端正常管理,可读的字节数为0,必须进行cancel操作。
                        * 忽视第二种情况会造成服务器程序宕机。忽视第三种情况会造成服务器的陷入死循环状态
                        * */
                        if(key.isReadable()){
                            try{
                                ByteBuffer buffer = ByteBuffer.allocate(16);
                                SocketChannel channel = (SocketChannel) key.channel();
                                int read = channel.read(buffer);
                                if(read == -1){
                                    key.cancel();
                                    channel.close();
                                }else{
                                    buffer.flip();
                                    printBytebuffer(buffer);
                                }
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                        }
                        iter.remove();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static void printBytebuffer(ByteBuffer tmp){      // 注意:传入的bytebuffer必须时写模式
        System.out.println(StandardCharsets.UTF_8.decode(tmp).toString());
    }
}

注意点:

  • wakeup 方法调用后能够让 selector.select() 立刻返回一次。
  • 利用 ConcurrentLinkedQueue 让 boss 线程将 runable 对象传递给 Worker 类的 register 函数,但是该函数实在 boss 线程中运行的。在 register 末尾唤醒,让 worker 线程实现 select。
利用 wakeup 解决可读事件无法获取的问题
// 哪个线程调用,在哪个线程执行!
public void register(SocketChannel sc) throws IOException {
    if(!start) { //第一次调用,初始化线程,和 selector
        selector = Selector.open();
        thread = new Thread(this, name);
        thread.start();
        start = true;
    }
    selector.wakeup(); // 唤醒 select 方法 boss
    sc.register(selector, SelectionKey.OP_READ, null); // boss线程
}

💡 无论 selector.select() 发生在 selector.wakeup() 前后都不会被阻塞!selector.wakeup()方法相当于给予 selector.select() 一张票,什么时候使用都可以,并不需要立即使用,即可以延迟使用。

多个 Worker 线程

程序功能:

1)定义一个 boss,其 selector 专门去监控客户端的 accept 事件。

2)定义实现 runable 接口的 worker 类,其 selector 专门用于监控客户端的读写事件。

3)使用单个 boss 多个 worker 处理客户端连接。

  • worker 的数量通常根据结合 cpu 核心数设置

4)采用 round-robin (轮询)机制让多个 work 均匀的监控客户端连接的读写事件。

  • 多线程环境下采用原子整数实现
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        //🍒 1. 创建固定数量的 worker 并初始化
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        AtomicInteger index = new AtomicInteger(); //🍒 原子计数
        while(true) {
            boss.select(); 
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}", sc.getRemoteAddress());
                    log.debug("before register...{}", sc.getRemoteAddress());
                    //🍒 2. 关联 selector
                    //🍒 round robin 轮询
                    workers[index.getAndIncrement() % workers.length].register(sc); // boss 调用 初始化 selector , 启动 worker-0
                    log.debug("after register...{}", sc.getRemoteAddress());
                }
            }
        }
    }
    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name; //线程名字
        private volatile boolean start = false; // 还未初始化!即线程没有执行过
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();
        public Worker(String name) {
            this.name = name;
        }

        // 哪个线程调用,在哪个线程执行!
        public void register(SocketChannel sc) throws IOException {
            if(!start) { //第一次调用,初始化线程,和 selector
                selector = Selector.open();
                thread = new Thread(this, name);
                thread.start();
                start = true;
            }
            selector.wakeup(); //🍒 唤醒 select 方法 boss
            sc.register(selector, SelectionKey.OP_READ, null); //🍒 boss线程
        }

        /**
         * 线程启动后,run方法内的代码,在Worker线程内启动
         */
        @Override
        public void run() {
            while(true) {
                try {
                    selector.select(); //🍒 worker-0  阻塞
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.debug("read...{}", channel.getRemoteAddress());
                            channel.read(buffer); //简单处理,不考虑半包、黏包、客户端关闭等情况
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

💡 如何拿到 cpu 个数

  • Runtime.getRuntime().availableProcessors() 如果工作在 docker 容器下,因为容器不是物理隔离的,会拿到物理 cpu 个数,而不是容器申请时的个数。
  • 这个问题直到 jdk 10 才修复,使用 jvm 参数 UseContainerSupport 配置,默认开启。

2.4.7 UDP

  • UDP 是无连接的,client 发送数据不会管 server 是否开启。
  • server 这边的 receive 方法会将接收到的数据存入 byte buffer,但如果数据报文超过 buffer 大小,多出来的数据会被默默抛弃。

【首先启动服务器端】

public class UdpServer {
    public static void main(String[] args) {
        try (DatagramChannel channel = DatagramChannel.open()) {
            channel.socket().bind(new InetSocketAddress(9999));
            System.out.println("waiting...");
            ByteBuffer buffer = ByteBuffer.allocate(32);
            channel.receive(buffer);
            buffer.flip();
            debug(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【运行客户端】

public class UdpClient {
    public static void main(String[] args) {
        try (DatagramChannel channel = DatagramChannel.open()) {
            ByteBuffer buffer = StandardCharsets.UTF_8.encode("hello");
            InetSocketAddress address = new InetSocketAddress("localhost", 9999);
            channel.send(buffer, address);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2.5 NIO vs BIO

2.5.1 stream vs channel

  • stream 不会自动缓冲数据(相对比较高层的 API,不关心底层缓冲区),channel 会利用系统提供的发送缓冲区、接收缓冲区(更为底层)
  • stream 仅支持阻塞 API,channel 同时支持阻塞、非阻塞 API,网络 channel 可配合 selector 实现多路复用
  • 二者均为全双工,即读写可以同时进行

2.5.2 IO 模型

同步阻塞、同步非阻塞、同步多路复用、异步阻塞(没有此情况)、异步非阻塞

  • 同步:线程自己去获取结果(一个线程)
  • 异步:线程自己不去获取结果,而是由其它线程送结果(至少两个线程)
read 模型

当调用一次 channel.read 或 stream.read 后,会切换至操作系统内核态来完成真正数据读取,而读取又分为两个阶段,分别为:

  • 等待数据阶段(即等待数据发送过来)
  • 复制数据阶段(即将数据从网卡读到内存)
阻塞 IO

当没有数据发送到接收端时,接收端的 read 用户线程被阻塞,读取期间什么活也干不了。

非阻塞 IO

用户线程一直在运行,没有数据则立即返回,然后接着调用 read 函数,直到有数据。

用户线程在复制数据时,还是会被阻塞住。即只有等待数据时是非阻塞。

多路复用

select 阻塞(等待数据时),当有事件发生时返回。read 在复制数据时阻塞。

信号驱动
异步 IO

异步:线程自己不去获取结果,而是由其它线程送结果(至少两个线程)

  • 阻塞 IO 于非阻塞 IO 都是同步操作,发起 read 的线程于接收数据的线程是同一个。

  • 多路复用本质上也是同步

异步模式:异步调用 read 时,定义了一个回调方法,有一个参数用来接收结果,这时候这个方法并没有调用,等内核读数据操作都完成了,另一个线程调用定义的回调方法,把真正读取到的结果作为参数传过去,完成两个线程之间数据的传递。

  • 通过上述描述可知,异步没有阻塞的情况。
阻塞 IO vs 多路复用

🔖 参考:《UNIX 网络编程 - 卷 I》

2.5.3 零拷贝

传统 IO 问题

传统的 IO 将一个文件通过 socket 写出

File f = new File("helloword/data.txt");
RandomAccessFile file = new RandomAccessFile(file, "r");

byte[] buf = new byte[(int)f.length()];
file.read(buf); //把文件读到数组中

Socket socket = ...;
socket.getOutputStream().write(buf);

内部工作流程如下:

  1. java 本身并不具备 IO 读写能力,因此 read 方法调用后,要从 java 程序的用户态切换至内核态,去调用操作系统(Kernel)的读能力,将数据读入内核缓冲区。这期间用户线程阻塞,操作系统使用 DMA(Direct Memory Access)来实现文件读,其间也不会使用 cpu。

    • DMA 也可以理解为硬件单元,用来解放 cpu 完成文件 IO。
  2. 从内核态切换回用户态,将数据从内核缓冲区读入用户缓冲区(即 byte[] buf),这期间 cpu 会参与拷贝,无法利用 DMA。

  3. 调用 write 方法,这时将数据从用户缓冲区(byte[] buf)写入 socket 缓冲区,cpu 会参与拷贝。

  4. 接下来要向网卡写数据,这项能力 java 又不具备,因此又得从用户态切换至内核态,调用操作系统的写能力,使用 DMA 将 socket 缓冲区的数据写入网卡,不会使用 cpu。

总结:可以看到中间环节较多,java 的 IO 实际不是物理设备级别的读写,而是缓存的复制,底层的真正读写是操作系统来完成的。

  • 用户态与内核态的切换发生了 3 次,这个操作比较重量级
  • 数据拷贝了共 4 次
NIO 优化
1) 通过 DirectByteBuf
  • ByteBuffer.allocate(10):HeapByteBuffer 使用的还是 java 内存

  • ByteBuffer.allocateDirect(10):DirectByteBuffer 使用的是操作系统内存(特点:操作系统可以访问、用户也可以访问

大部分步骤与优化前相同,不再赘述。唯有一点:java 可以使用 DirectByteBuf 将堆外内存映射到 jvm 内存中来直接访问使用。

  • 这块内存不受 jvm 垃圾回收的影响,因此内存地址固定,有助于 IO 读写
  • java 中的 DirectByteBuf 对象仅维护了此内存的虚引用,内存回收分成两步
    • DirectByteBuf 对象被垃圾回收,将虚引用加入引用队列
    • 通过专门线程访问引用队列,根据虚引用释放堆外内存
  • 减少了一次数据拷贝,用户态与内核态的切换次数没有减少
2) 进一步优化(linux 2.1)

进一步优化(底层采用了 linux 2.1 后提供的 sendFile 方法),java 中对应着两个 channel 调用 transferTo/transferFrom 方法拷贝数据。

  1. java 调用 transferTo 方法后,要从 java 程序的用户态切换至内核态,使用 DMA将数据读入内核缓冲区,不会使用 cpu
  2. 数据从内核缓冲区传输到 socket 缓冲区,cpu 会参与拷贝
  3. 最后使用 DMA 将 socket 缓冲区的数据写入网卡,不会使用 cpu

可以看到

  • 只发生了一次用户态与内核态的切换
  • 数据拷贝了 3 次
3) 进一步优化(linux 2.4)
  1. java 调用 transferTo 方法后,要从 java 程序的用户态切换至内核态,使用 DMA将数据读入内核缓冲区,不会使用 cpu
  2. 只会将一些 offset 和 length 信息拷入 socket 缓冲区,几乎无消耗
  3. 使用 DMA 将 内核缓冲区的数据写入网卡,不会使用 cpu

整个过程仅只发生了一次用户态与内核态的切换,数据拷贝了 2 次。

所谓的【零拷贝】,并不是真正无拷贝,而是在不会拷贝重复数据到 jvm 内存中,零拷贝的优点有

  • 更少的用户态与内核态的切换
  • 不利用 cpu 计算,减少 cpu 缓存伪共享
  • 零拷贝适合小文件传输

2.5.4 AIO

AIO 用来解决数据复制阶段的阻塞问题

  • 同步意味着,在进行读写操作时,线程需要等待结果,还是相当于闲置。

  • 异步意味着,在进行读写操作时,线程不必等待结果,而是将来由操作系统来通过回调方式由另外的线程来获得结果。

异步模型需要底层操作系统(Kernel)提供支持

  • Windows 系统通过 IOCP 实现了真正的异步 IO。
  • Linux 系统异步 IO 在 2.6 版本引入,但其底层实现还是用多路复用模拟了异步 IO,性能没有优势。
文件 AIO
  • AsynchronousFileChannel
package cn.itcast.nio.c5;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static cn.itcast.nio.c2.ByteBufferUtil.debugAll;

@Slf4j
public class AioFileChannel {
    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)) {
            // 参数1 ByteBuffer 用于接收结果
            // 参数2 读取的起始位置
            // 参数3 附件(一次读取不能读完时,用于读取剩下的数据)
            // 参数4 回调对象 CompletionHandler
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.debug("read begin...");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override // read 成功
                //para1 result 读到的实际字节数
                public void completed(Integer result, ByteBuffer attachment) { //在其他线程执行--是一个守护线程
                    log.debug("read completed...{}", result);
                    attachment.flip();
                    debugAll(attachment);
                }
                @Override // read 失败
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end...");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //其他线程都结束了,守护线程也会结束,无论其是否运行完
        System.in.read();
    }
}

💡 守护线程:默认文件 AIO 使用的线程都是守护线程,所以最后要执行 System.in.read() 以避免守护线程意外结束

网络 AIO
public class AioServer {
    public static void main(String[] args) throws IOException {
        AsynchronousServerSocketChannel ssc = AsynchronousServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.accept(null, new AcceptHandler(ssc));
        System.in.read();
    }

    private static void closeChannel(AsynchronousSocketChannel sc) {
        try {
            System.out.printf("[%s] %s close\n", Thread.currentThread().getName(), sc.getRemoteAddress());
            sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {
        private final AsynchronousSocketChannel sc;

        public ReadHandler(AsynchronousSocketChannel sc) {
            this.sc = sc;
        }

        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            try {
                if (result == -1) {
                    closeChannel(sc);
                    return;
                }
                System.out.printf("[%s] %s read\n", Thread.currentThread().getName(), sc.getRemoteAddress());
                attachment.flip();
                System.out.println(Charset.defaultCharset().decode(attachment));
                attachment.clear();
                // 处理完第一个 read 时,需要再次调用 read 方法来处理下一个 read 事件
                sc.read(attachment, attachment, this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            closeChannel(sc);
            exc.printStackTrace();
        }
    }

    private static class WriteHandler implements CompletionHandler<Integer, ByteBuffer> {
        private final AsynchronousSocketChannel sc;

        private WriteHandler(AsynchronousSocketChannel sc) {
            this.sc = sc;
        }

        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            // 如果作为附件的 buffer 还有内容,需要再次 write 写出剩余内容
            if (attachment.hasRemaining()) {
                sc.write(attachment);
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            exc.printStackTrace();
            closeChannel(sc);
        }
    }

    private static class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Object> {
        private final AsynchronousServerSocketChannel ssc;

        public AcceptHandler(AsynchronousServerSocketChannel ssc) {
            this.ssc = ssc;
        }

        @Override
        public void completed(AsynchronousSocketChannel sc, Object attachment) {
            try {
                System.out.printf("[%s] %s connected\n", Thread.currentThread().getName(), sc.getRemoteAddress());
            } catch (IOException e) {
                e.printStackTrace();
            }
            ByteBuffer buffer = ByteBuffer.allocate(16);
            // 读事件由 ReadHandler 处理
            sc.read(buffer, buffer, new ReadHandler(sc));
            // 写事件由 WriteHandler 处理
            sc.write(Charset.defaultCharset().encode("server hello!"), ByteBuffer.allocate(16), new WriteHandler(sc));
            // 处理完第一个 accpet 时,需要再次调用 accept 方法来处理下一个 accept 事件
            ssc.accept(null, this);
        }

        @Override
        public void failed(Throwable exc, Object attachment) {
            exc.printStackTrace();
        }
    }
}

资料

💡 调试工具类 ByteBufferUtil

public class ByteBufferUtil {
    private static final char[] BYTE2CHAR = new char[256];
    private static final char[] HEXDUMP_TABLE = new char[256 * 4];
    private static final String[] HEXPADDING = new String[16];
    private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
    private static final String[] BYTE2HEX = new String[256];
    private static final String[] BYTEPADDING = new String[16];

    static {
        final char[] DIGITS = "0123456789abcdef".toCharArray();
        for (int i = 0; i < 256; i++) {
            HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
            HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
        }

        int i;

        // Generate the lookup table for hex dump paddings
        for (i = 0; i < HEXPADDING.length; i++) {
            int padding = HEXPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding * 3);
            for (int j = 0; j < padding; j++) {
                buf.append("   ");
            }
            HEXPADDING[i] = buf.toString();
        }

        // Generate the lookup table for the start-offset header in each row (up to 64KiB).
        for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
            StringBuilder buf = new StringBuilder(12);
            buf.append(NEWLINE);
            buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
            buf.setCharAt(buf.length() - 9, '|');
            buf.append('|');
            HEXDUMP_ROWPREFIXES[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-hex-dump conversion
        for (i = 0; i < BYTE2HEX.length; i++) {
            BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
        }

        // Generate the lookup table for byte dump paddings
        for (i = 0; i < BYTEPADDING.length; i++) {
            int padding = BYTEPADDING.length - i;
            StringBuilder buf = new StringBuilder(padding);
            for (int j = 0; j < padding; j++) {
                buf.append(' ');
            }
            BYTEPADDING[i] = buf.toString();
        }

        // Generate the lookup table for byte-to-char conversion
        for (i = 0; i < BYTE2CHAR.length; i++) {
            if (i <= 0x1f || i >= 0x7f) {
                BYTE2CHAR[i] = '.';
            } else {
                BYTE2CHAR[i] = (char) i;
            }
        }
    }

    /**
     * 打印所有内容
     * @param buffer
     */
    public static void debugAll(ByteBuffer buffer) {
        int oldlimit = buffer.limit();
        buffer.limit(buffer.capacity());
        StringBuilder origin = new StringBuilder(256);
        appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
        System.out.println("+--------+-------------------- all ------------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
        System.out.println(origin);
        buffer.limit(oldlimit);
    }

    /**
     * 打印可读取内容
     * @param buffer
     */
    public static void debugRead(ByteBuffer buffer) {
        StringBuilder builder = new StringBuilder(256);
        appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
        System.out.println("+--------+-------------------- read -----------------------+----------------+");
        System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
        System.out.println(builder);
    }

    private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
        if (isOutOfBounds(offset, length, buf.capacity())) {
            throw new IndexOutOfBoundsException(
                    "expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
                            + ") <= " + "buf.capacity(" + buf.capacity() + ')');
        }
        if (length == 0) {
            return;
        }
        dump.append(
                "         +-------------------------------------------------+" +
                        NEWLINE + "         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |" +
                        NEWLINE + "+--------+-------------------------------------------------+----------------+");

        final int startIndex = offset;
        final int fullRows = length >>> 4;
        final int remainder = length & 0xF;

        // Dump the rows which have 16 bytes.
        for (int row = 0; row < fullRows; row++) {
            int rowStartIndex = (row << 4) + startIndex;

            // Per-row prefix.
            appendHexDumpRowPrefix(dump, row, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + 16;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(" |");

            // ASCII dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append('|');
        }

        // Dump the last row which has less than 16 bytes.
        if (remainder != 0) {
            int rowStartIndex = (fullRows << 4) + startIndex;
            appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);

            // Hex dump
            int rowEndIndex = rowStartIndex + remainder;
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
            }
            dump.append(HEXPADDING[remainder]);
            dump.append(" |");

            // Ascii dump
            for (int j = rowStartIndex; j < rowEndIndex; j++) {
                dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
            }
            dump.append(BYTEPADDING[remainder]);
            dump.append('|');
        }

        dump.append(NEWLINE +
                "+--------+-------------------------------------------------+----------------+");
    }

    private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
        if (row < HEXDUMP_ROWPREFIXES.length) {
            dump.append(HEXDUMP_ROWPREFIXES[row]);
        } else {
            dump.append(NEWLINE);
            dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
            dump.setCharAt(dump.length() - 9, '|');
            dump.append('|');
        }
    }

    public static short getUnsignedByte(ByteBuffer buffer, int index) {
        return (short) (buffer.get(index) & 0xFF);
    }
}
posted @ 2021-09-18 14:32  喵喵巫  阅读(739)  评论(0编辑  收藏  举报