1、Buffer简介
Buffer本质是一个内存块,既可以写入数据,也可以读出数据。
java.nio中的Buffer类是一个非线程安全的类
Buffer类型说明:
**
Buffer是一个抽象类,对应于java的主要数据类型,nio中有8种缓冲区,分别如下
- ByteBuffer : 使用最多的Buffer
- CharBuffer
- ShortBuffer
- IntBuffer
- DoubleBufffer
- LongBuffer
- FloatBuffer
- MappedByteBuffer :专门用于内存映射
Buffer属性说明
capacity 容量,即可以容纳的最大数据量;在缓冲区创建时设置并且不能改变
limit 上限,缓冲区中当前的数据量
position 读写指针,缓冲区中下一个要被读或写的元素的索引
mark 标记,调用 mark()方法来设置 mark=position,再调用 reset()可以让 position 恢复到 mark 标记的位置即 position=mark
ByteBuffer 有以下重要属性
- capacity
- position
- limit
一开始

写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态
flip 动作发生后,position 切换为读取位置,limit 切换为读取限制
读取 4 个字节后,状态
clear 动作发生后,状态
compact 方法,是把未读完的部分向前压缩,然后切换至写模式

Buffer使用步骤:
(1)使用创建子类实例对象的 allocate()方法,创建一个 Buffer 类的实例对象。
(2)调用 put 方法,将数据写入到缓冲区中。
(3)写入完成后,在开始读取数据前,调用 Buffer.flip()方法,将缓冲区转换为读模式。
(4)调用 get 方法,从缓冲区中读取数据。
(5)读取完成后,调用 Buffer.clear() 或 Buffer.compact()方法,将缓冲区转换为写入模式。
2、Buffer实战
2.1、Buffer调试工具类
package com.jx.netty.niobase.util;import io.netty.util.internal.StringUtil;import java.nio.ByteBuffer;import static io.netty.util.internal.StringUtil.NEWLINE;import static io.netty.util.internal.MathUtil.isOutOfBounds;/*** @Description:* @Author: zhangjx* @Date: 2021-05-07**/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 paddingsfor (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 conversionfor (i = 0; i < BYTE2HEX.length; i++) {BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);}// Generate the lookup table for byte dump paddingsfor (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 conversionfor (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 dumpint rowEndIndex = rowStartIndex + 16;for (int j = rowStartIndex; j < rowEndIndex; j++) {dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);}dump.append(" |");// ASCII dumpfor (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 dumpint rowEndIndex = rowStartIndex + remainder;for (int j = rowStartIndex; j < rowEndIndex; j++) {dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);}dump.append(HEXPADDING[remainder]);dump.append(" |");// Ascii dumpfor (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);}}
2.2、Buffer使用示例
public static void main(String[] args) {IntBuffer intBuffer = IntBuffer.allocate(10);for (int i = 0; i < 5; i++) {intBuffer.put(i);System.out.println("写模式: position: " + intBuffer.position() + " limit: " + intBuffer.limit() + " capacity: " + intBuffer.capacity());}//将缓冲区切换为读模式intBuffer.flip();for (int i = 0; i < 5; i++) {System.out.println("读取: " + intBuffer.get() + " 读模式: position: " + intBuffer.position() + " limit: " + intBuffer.limit() + " capacity: " + intBuffer.capacity());}//rewind 倒带已经读完的数据,再读一遍intBuffer.rewind();for (int i = 0; i < 5; i++) {System.out.println("读取: " + intBuffer.get() + " 读模式: position: " + intBuffer.position() + " limit: " + intBuffer.limit() + " capacity: " + intBuffer.capacity());}//mark 和 resetintBuffer.rewind();for (int i = 0; i < 5; i++) {if(i == 2){intBuffer.mark();}System.out.println("读取: " + intBuffer.get() + " 读模式: position: " + intBuffer.position() + " limit: " + intBuffer.limit() + " capacity: " + intBuffer.capacity());}intBuffer.reset();System.out.println("读取: " + intBuffer.get() + " 读模式: position: " + intBuffer.position() + " limit: " + intBuffer.limit() + " capacity: " + intBuffer.capacity());//clear 清空缓冲区intBuffer.clear();intBuffer.put(1);System.out.println("读取: " + intBuffer.get() + " 读模式: position: " + intBuffer.position() + " limit: " + intBuffer.limit() + " capacity: " + intBuffer.capacity());}
2.3、字符串和ByteBuffer互相转化
//字符串转为ByteBuffer
//1、转为字节数组,写入ByteBuffer,仍处于写模式
ByteBuffer strBuffer1 = ByteBuffer.allocate(16);
strBuffer1.put( "hello".getBytes());
ByteBufferUtil.debugAll(strBuffer1);
//2、Charset 自动切换为读模式
ByteBuffer strBuffer2 = StandardCharsets.UTF_8.encode("hello");
ByteBufferUtil.debugAll(strBuffer2);
//3、wrap 自动切换为读模式
ByteBuffer strBuffer3 = ByteBuffer.wrap("hello".getBytes());
ByteBufferUtil.debugAll(strBuffer3);
//ByteBuffer转为字符串
//strBuffer1仍然处于写模式,无法转为字符串
String s1 = StandardCharsets.UTF_8.decode(strBuffer1).toString();
System.out.println("s1: " + s1);
String s2 = StandardCharsets.UTF_8.decode(strBuffer2).toString();
System.out.println("s2: " +s2);
2.4、ByteBuffer 黏包,半包问题
网络上有多条数据发送给服务端,数据之间使用 \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 分隔的数据
public class ByteBufferExam {
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();
for (int i = 0; i < source.limit() ; i++) {
if (source.get(i) == '\n'){
int len = i + 1 - source.position();
ByteBuffer buffer = ByteBuffer.allocate(len);
for (int j = 0; j < len; j++) {
byte b = source.get();
buffer.put(b);
}
ByteBufferUtil.debugAll(buffer);
}
}
source.compact();
}
}
