ByteBuffer作为JDK的字节流处理对象,这里举个小例子说明下用法,直接上代码:

package com.wlf.netty.nettyserver;

import org.junit.Assert;
import org.junit.Test; import java.nio.ByteBuffer; public class ByteBufferTest { @Test
public void byteBufferTest() { // 写入消息体
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
byteBuffer.putInt(0xabef0101);
byteBuffer.putInt(1024); // 今天过节
byteBuffer.put((byte) 1);
byteBuffer.put((byte) 0); // 读取消息头,因为写完后position已经到10了,所以需要先反转为0,再从头读取
byteBuffer.flip();
printDelimiter(byteBuffer); // 读取length
printLength(byteBuffer); // 继续读取剩下数据
byteBuffer.get();
byteBuffer.get();
printByteBuffer(byteBuffer); // 我再反转一下,我还可以从头开始读
byteBuffer.flip();
printDelimiter(byteBuffer); // clear清空一下,再从头开始读
byteBuffer.clear();
printDelimiter(byteBuffer); // rewind重绕一下
byteBuffer.rewind();
printDelimiter(byteBuffer); // mark标记一下
byteBuffer.mark(); // 再读取length
printLength(byteBuffer); // reset重置,回到读取delimiter的地方
byteBuffer.reset();
printByteBuffer(byteBuffer);
} private void printDelimiter(ByteBuffer buf) {
int newDelimiter = buf.getInt();
System.out.printf("delimeter: %s\n", Integer.toHexString(newDelimiter));
printByteBuffer(buf);
} private void printLength(ByteBuffer buf) {
int length = buf.getInt();
System.out.printf("length: %d\n", length);
printByteBuffer(buf);
} private void printByteBuffer(ByteBuffer buf) {
System.out.printf("position: %d, limit: %d, capacity: %d\n", buf.position(), buf.limit(), buf.capacity());
}
}

  输出结果:

delimeter: abef0101
position: 4, limit: 10, capacity: 10
length: 1024
position: 8, limit: 10, capacity: 10
position: 10, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
length: 1024
position: 8, limit: 10, capacity: 10
position: 4, limit: 10, capacity: 10 Process finished with exit code 0

  ByteBuffer的索引是唯一的。像上面的例子,初始索引是0,写完索引值为9,为了读取写入的值,我们再重新设置索引为0(调用flip方法)。ByteBuffer有4个索引值,分别是:

  mask:就是你标记的索引,标记唯一的作用是调用reset重置回到过去

  position:当前位置的索引,mask标记任何时候都不会大于position,因为你必须先读到当前位置之后,才能标记该位置;同时position也不能超过limit限制

  limit:第一个不应该读取或写入的元素的索引,也就是读写禁地,默认是最大容量,如果你设置该值,那么理所让然它不能超过最大容量capacity

  capacity:这个就不解释了

  它们的大小关系始终是:

  mask <= position <= limit <= capacity

  我们上面的例子中就是capacity=limit。

  初始索引:

  +-----------------------------------------------------+

/                            bytes                              /

+-----------------------------------------------------+

/                            10                                  /

  0=position                                               10=limit=capacity

  我们写入delimiter之后:

  +----------------+------------------------------------+

/      delimiter /     other  bytes                       /

+----------------+------------------------------------+

/             4     /          6                                    /

   0        4=position                                     10=limit=capacity

  

  至于反转flip如何切换读写模式、reset如何重置标记、clear清除如何重新设置索引值为0、rewind重绕如何让你重新读取,都不会动内容,所以你会看到上面不管怎么折腾我们都可以重复取出delimiter、length的值。看下源码就一清二楚了,无非就是对上面4个索引值进行赋值而已:

    /**
* Resets this buffer's position to the previously-marked position.
*
* <p> Invoking this method neither changes nor discards the mark's
* value. </p>
*
* @return This buffer
*
* @throws InvalidMarkException
* If the mark has not been set
*/
public final Buffer reset() {
int m = mark;
if (m < 0)
throw new InvalidMarkException();
position = m;
return this;
} /**
* Clears this buffer. The position is set to zero, the limit is set to
* the capacity, and the mark is discarded.
*
* <p> Invoke this method before using a sequence of channel-read or
* <i>put</i> operations to fill this buffer. For example:
*
* <blockquote><pre>
* buf.clear(); // Prepare buffer for reading
* in.read(buf); // Read data</pre></blockquote>
*
* <p> This method does not actually erase the data in the buffer, but it
* is named as if it did because it will most often be used in situations
* in which that might as well be the case. </p>
*
* @return This buffer
*/
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
} /**
* Flips this buffer. The limit is set to the current position and then
* the position is set to zero. If the mark is defined then it is
* discarded.
*
* <p> After a sequence of channel-read or <i>put</i> operations, invoke
* this method to prepare for a sequence of channel-write or relative
* <i>get</i> operations. For example:
*
* <blockquote><pre>
* buf.put(magic); // Prepend header
* in.read(buf); // Read data into rest of buffer
* buf.flip(); // Flip buffer
* out.write(buf); // Write header + data to channel</pre></blockquote>
*
* <p> This method is often used in conjunction with the {@link
* java.nio.ByteBuffer#compact compact} method when transferring data from
* one place to another. </p>
*
* @return This buffer
*/
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
} /**
* Rewinds this buffer. The position is set to zero and the mark is
* discarded.
*
* <p> Invoke this method before a sequence of channel-write or <i>get</i>
* operations, assuming that the limit has already been set
* appropriately. For example:
*
* <blockquote><pre>
* out.write(buf); // Write remaining data
* buf.rewind(); // Rewind buffer
* buf.get(array); // Copy data into array</pre></blockquote>
*
* @return This buffer
*/
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}

ByteBuffer使用实例的更多相关文章

  1. ByteBuffer常用方法详解

    原文  http://blog.csdn.net/u012345283/article/details/38357851 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I/ ...

  2. ByteBuf使用实例

    之前我们有个netty5的拆包解决方案(参加netty5拆包问题解决实例),现在我们采用另一种思路,不需要新增LengthFieldBasedFrameDecoder,直接修改NettyMessage ...

  3. JAVA NIO缓冲区(Buffer)------ByteBuffer常用方法

    参考:https://blog.csdn.net/xialong_927/article/details/81044759 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I ...

  4. Java性能优化之使用NIO提升性能(Buffer和Channel)

    在软件系统中,由于IO的速度要比内存慢,因此,I/O读写在很多场合都会成为系统的瓶颈.提升I/O速度,对提升系统整体性能有着很大的好处. 在Java的标准I/O中,提供了基于流的I/O实现,即Inpu ...

  5. Java NIO Buffer(netty源码死磕1.2)

    [基础篇]netty源码死磕1.2:  NIO Buffer 1. Java NIO Buffer Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区.Buffer缓冲区本质上是一块可 ...

  6. JAVA NIO学习笔记二 频道和缓冲区

    Java NIO 频道 Java NIO渠道类似于流,他们之间具有一些区别的: 您可以读取和写入频道.流通常是单向(读或写). 通道可以异步读取和写入数据. 通道常常是读取或写入缓冲区. 如上所述,您 ...

  7. LWJGL3的内存管理,第一篇,基础知识

    LWJGL3的内存管理,第一篇,基础知识 为了讨论LWJGL在内存分配方面的设计,我将会分为数篇随笔分开介绍,本篇将主要介绍一些大方向的问题和一些必备的知识. 何为"绑定(binding)& ...

  8. 最近学习工作流 推荐一个activiti 的教程文档

    全文地址:http://www.mossle.com/docs/activiti/ Activiti 5.15 用户手册 Table of Contents 1. 简介 协议 下载 源码 必要的软件 ...

  9. RPC原理及RPC实例分析

    在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...

随机推荐

  1. CF1167E. Range Deleting

    题意 给定长度为\(n\)的数组\(a\),其中任意\(a_i \leq x\) 定义\(f(l,r)\)为删除\(a\)中值域在\([l,r]\)的数后剩余的数组. 统计满足\(1\leq l \l ...

  2. 实现多层DIV叠加的js事件穿透

    前几天做的一个功能:在地图上加载标注,这个标注是列表,就直接放的 DIV. 后来发现,当鼠标在这个标注上面的时候,滚动鼠标滚轮,地图的缩放功能失效. 想了下,应该是最上面的标注 DIV 拦截了滚轮滚动 ...

  3. 《hello-world》第九次团队作业:【Beta】Scrum meeting 1

    项目 内容 这个作业属于哪个课程 2016级计算机科学与工程学院软件工程(西北师范大学) 这个作业的要求在哪里 实验十三 团队作业9:Beta冲刺与团队项目验收 团队名称 <hello--wor ...

  4. “只有DBA才能导入由其他DBA导出的文件”各种解决办法

    “只有DBA才能导入由其他DBA导出的文件”各种解决办法 当oracle导入的时候出现“只有 DBA 才能导入由其他 DBA 导出的文件”的时候通常有以下几种解决办法! 1:常见的是直接grant   ...

  5. centos 环境下安装maven

    安装Maven Maven的下载地址:http://maven.apache.org/download.cgi这里以最新的3.2.3版本为例进行安装,在这之前需要确保机器上已经安装了JDK. 首先下载 ...

  6. koa2-router中间件来请求数据获取

    原理 虽然不使用中间件也能获取请求数据 对于POST请求的处理,koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中. 安装koa2版本 ...

  7. house买房原理,2019,第一版

    ,购买框架 1,通过自己的买房预算金额 和 pre-approval 确定你要的房屋总价, 估计到自己可以接受的房子,卖方也喜欢这样的买家,但不一定能拿全额贷款 2,pre-approval对信用分数 ...

  8. node.js Error: connect EMFILE 或者 getaddrinfo ENOTFOUND

    Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' Error: c ...

  9. 在linux中设置优先使用ipv4,而不是ipv6

    背景: 有时候更新源的时候默认使用ipv6,而ipv6下载数据时候总出现问题. 所有想默认出口的时候优先使用ipv4出口访问,而不是ipv6. 要使用ipv4 连接优先而不必禁用ipv6,需要修改ga ...

  10. Cayley-Hamilton定理与矩阵快速幂优化、常系数线性递推优化

    原文链接www.cnblogs.com/zhouzhendong/p/Cayley-Hamilton.html Cayley-Hamilton定理与矩阵快速幂优化.常系数线性递推优化 引入 在开始本文 ...