ByteBuffer使用实例
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使用实例的更多相关文章
- ByteBuffer常用方法详解
原文 http://blog.csdn.net/u012345283/article/details/38357851 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I/ ...
- ByteBuf使用实例
之前我们有个netty5的拆包解决方案(参加netty5拆包问题解决实例),现在我们采用另一种思路,不需要新增LengthFieldBasedFrameDecoder,直接修改NettyMessage ...
- JAVA NIO缓冲区(Buffer)------ByteBuffer常用方法
参考:https://blog.csdn.net/xialong_927/article/details/81044759 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I ...
- Java性能优化之使用NIO提升性能(Buffer和Channel)
在软件系统中,由于IO的速度要比内存慢,因此,I/O读写在很多场合都会成为系统的瓶颈.提升I/O速度,对提升系统整体性能有着很大的好处. 在Java的标准I/O中,提供了基于流的I/O实现,即Inpu ...
- Java NIO Buffer(netty源码死磕1.2)
[基础篇]netty源码死磕1.2: NIO Buffer 1. Java NIO Buffer Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区.Buffer缓冲区本质上是一块可 ...
- JAVA NIO学习笔记二 频道和缓冲区
Java NIO 频道 Java NIO渠道类似于流,他们之间具有一些区别的: 您可以读取和写入频道.流通常是单向(读或写). 通道可以异步读取和写入数据. 通道常常是读取或写入缓冲区. 如上所述,您 ...
- LWJGL3的内存管理,第一篇,基础知识
LWJGL3的内存管理,第一篇,基础知识 为了讨论LWJGL在内存分配方面的设计,我将会分为数篇随笔分开介绍,本篇将主要介绍一些大方向的问题和一些必备的知识. 何为"绑定(binding)& ...
- 最近学习工作流 推荐一个activiti 的教程文档
全文地址:http://www.mossle.com/docs/activiti/ Activiti 5.15 用户手册 Table of Contents 1. 简介 协议 下载 源码 必要的软件 ...
- RPC原理及RPC实例分析
在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...
随机推荐
- Linux 服务器性能出问题,排查下这些参数指标
taozj马哥Linux运维 一个基于 Linux 操作系统的服务器运行的同时,也会表征出各种各样参数信息.通常来说运维人员.系统管理员会对这些数据会极为敏感,但是这些参数对于开发者来说也十分重要,尤 ...
- python_并发编程——多进程
from multiprocessing import Process import os def func1(): print('子进程1',os.getpid()) #子进程:获取当前进程的进程号 ...
- git常用命令总结--原创
0.git status 仓库状态1.git add 工作区-->暂存区2.git commit 暂存区-->版本库3.git log 查看日志4.git reset --hard hea ...
- 题解 UVa10780
题目大意 多组数据,每组数据给定两个整数 \(m,n\),输出使 \(n\%m^k=0\) 的最大的 \(k\).如果 \(k=0\) 则输出Impossible to divide. 分析 计数水题 ...
- zookeeper先验知识(2PC+paxos)
一.2PC两阶段提交: 在分布式事务中,每个机器节点只能够明确知道自己事务操作的结果,是成功还是失败,而无法获取其他分布式节点的操作结果,因此在事务操作需要跨多个分布式节点时,需要引入一个协调者统一调 ...
- vue创建组件的方式
一.直接通过Vue.extend的方式创建组件 // 通过vue.extend 来创建全局组件 var com1 = Vue.extend({ template:'<h3>这是h3组件&l ...
- ES 基础理论 配置调优
一.简介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasticsearch是用Java开发的,并作为 ...
- C利用可变参数列表统计一组数的平均值,利用函数形式参数栈原理实现指针运算
//描述:利用可变参数列表统计一组数的平均值 #include <stdarg.h> #include <stdio.h> float average(int num, ... ...
- leetcode解题报告(27):Reverse Linked List
描述 Reverse a singly linked list. 分析 一开始写的时候总感觉没抓到要点,然后想起上数据结构课的教材上有这道题,翻开书一看完就回忆起来了,感觉解法挺巧妙的,不比讨论区的答 ...
- Problem 8 dp
$des$ $sol$ 记 $f_i$ 表示考虑前 $i$ 个建筑, 并且第 $i$ 个建筑的高度不变的答案, 每次转移时枚举上一个不变的建筑编号, 中间的一段一定变成相同的高度, 并且高度小于等于两 ...