NIO基础
NIO:non- blocking io非阻塞
1.三大组件
1.1 Channel & Buffer
channel(通道的意思)有一点类似于 stream,它就是读写数据的双向通道,可以从 channel将数据读入 buffer,也可以将buffer的数据写入 channel,而之前的 stream要么是输入,要么是输出, channel比 stream更为底层
常见的 Channel有
- FileChannel(文件传输通道)
- DatagramChannel(UDP传输通道)
- Socke Channel(TCP传输通道)
- ServersocketChannel(TCP传输通道)
buffer则用来缓冲读写数据,常见的 buffer有
Bytebuffer
- MappedbyteBuffer
- Directbytebuffero
- HeapbyteBuffer
- ShortBuffer
- IntBuffer
- Longbuffer
- FloatBuffer
- DoubleBuffer
1.2 Selector
selector单从字面意思不好理解,需要结合服务器的设计演化来理解它的用途
多线程版设计
多线程版缺点
- 内存占用高
- 线程上下文切换成本高
- 只适合连接数少的场景
线程池设计
- 阻塞模式下,线程仅能处理一个socket连接
- 仅适合短连接场景
selector版设计
selector的作用就是配合一个线程来管理多个 channel,获取这些 channel上发生的事件,这些 channel工作在非阻塞模式下,不会让线程吊死在一个 channel上。适合连接数特别多,但流量低的场景(Low traffic)
调用 selector I的 select0会阻塞直到 channel发生了读写就緒事件,这些事件发生, select方法就会返回这些事件交给 thread来处理
2.ByteBuffer
1.ByteBuffer代码
package com.gaoxu.netty;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
@Slf4j
public class TestBuffer {
public static void main(String[] args) throws FileNotFoundException {
//FileChannel
//1.输入输出流,2.RandomAccessFile
try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
//准备缓冲区
ByteBuffer buffer = ByteBuffer.allocate(10);
while (true) {
//从channel读取文件,向buffer写入
int len = channel.read(buffer);
log.debug("读取的字节:{}",len);
if (len<1){
break;
}
//打印buffer内容
buffer.flip();//切换buffer的读模式
while (buffer.hasRemaining()) {//buffer.hasRemaining()判断是否有剩余
byte b = buffer.get();//获取一个字节
System.out.print((char) b);
log.debug("读取的字节:{}",(char) b);
}
buffer.clear();//切换为写模式
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.ByteBuffer结构
ByteBuffer有以下重要属性
- capacity
- position
limit
一开始
写模式下, position是写入位置, limit等于容量,下图表示写入了4个字节后的状态
filp动作发生后, position切换为读取位置,limit切换为读取限制
3.ByteBuffer常用方法
分配空间
可以使用 allocate 方法为 ByteBuffer 分配空间,其它 buffer 类也有该方法
Bytebuffer buf = ByteBuffer.allocate(16);
package com.gaoxu.netty;
import java.nio.ByteBuffer;
public class Testbytebufferallocate {
public static void main(String[] args) {
/*
1.class java nio. Heapbytebuffer
java堆内存,读写效率较低,受到GC的影响
2.class java.nio.DirectBytebuffer
直接内存,读写效率高(少一次拷贝),不会受GC影响,分配的效率
*/
System.out.println(ByteBuffer.allocate(16));
System.out.println(ByteBuffer.allocateDirect(16));
}
}
向 buffer 写入数据
有两种办法
- 调用 channel 的 read 方法
调用 buffer 自己的 put 方法
int readBytes = channel.read(buf); //和 buf.put((byte)127);
从 buffer 读取数据
同样有两种办法
- 调用 channel 的 write 方法
调用 buffer 自己的 get 方法
int writeBytes = channel.write(buf); //和 byte b = buf.get(); //get(i)方法不会改变指针位置 byte c = buf.get(i);
get 方法会让 position 读指针向后走,如果想重复读取数据
- 可以调用 rewind 方法将 position 重新置为 0
- 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针
mark 和 reset
mark 是在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置
注意
rewind 和 flip 都会清除 mark 位置
bytebuffer工具类
import io.netty.util.internal.StringUtil;
import java.nio.ByteBuffer;
import static io.netty.util.internal.MathUtil.isOutOfBounds;
import static io.netty.util.internal.StringUtil.NEWLINE;
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);
}
}
测试类
package com.gaoxu.netty;
import java.nio.ByteBuffer;
import static com.gaoxu.netty.util.ByteBufferUtil.debugAll;
public class Main {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put((byte) 0x61);
buffer.put(new byte[]{0x62,0x63,0x64});
debugAll(buffer);
buffer.flip();
System.out.println(buffer.get());
debugAll(buffer);
buffer.compact();
debugAll(buffer);
buffer.put(new byte[]{0x65,0x6a});
debugAll(buffer);
}
}
运行结果
2021-11-04 01:41:15,049 DEBUG [io.netty.util.internal.logging.InternalLoggerFactory] - Using SLF4J as the default logging framework
+--------+-------------------- all ------------------------+----------------+
position: [4], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00 |abcd...... |
+--------+-------------------------------------------------+----------------+
97
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [4]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 64 00 00 00 00 00 00 |abcd...... |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [3], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 64 00 00 00 00 00 00 |bcdd...... |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [10]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 65 6a 00 00 00 00 00 |bcdej..... |
+--------+-------------------------------------------------+----------------+
Process finished with exit code 0
[...]Docker容器 -2021Dubbo框架 -2020Git版本控制-20180Golang语言入门-2021Java设计模式-2019JVM探究-2019Mybatis框架-2019MySQL数据库-2019Netty网络编程框架-2021Redis数据库-2020SMS框架整合-2019Spring框架-2018Springboot框架-2019Springmvc框架-2019SVN版本控制-[...]