`

mina通讯框架详述(IoBuffer)

 
阅读更多

IoBuffer

1.获取IoBuffer对象:(IoBuffer是一个抽象类,因此不能直接实例化)

 

 

// 使用指定大小实例化一个新的Buffer, 并且可以定义他的类型 (direct 或 heap)   
public static IoBuffer allocate(int capacity, boolean direct)   
// 使用指定大小实例化一个新的Buffer   
public static IoBuffer allocate(int capacity)  
 

 

第二种方式:(使用第二种方法之前你必须先指定Buffer类型,否则默认将是Heap)

 

 

// 设置创建默认Buffer的类型,这里是heap.  
 IoBuffer.setUseDirectBuffer(false);   
// 新建一个Buffer   
IoBuffer buf = IoBuffer.allocate(1024); 

 

 

 

2.IoBuffer的自动扩展:(使用Java NIO的API创建一个可扩展的buffer并不容易,因为要为网络程序填充超过固定大小数据)

 

 

IoBuffer buffer = IoBuffer.allocate(8);  
buffer.setAutoExpand(true);  
  
buffer.putString("12345678", encoder);  
         
// 往Buffer里加入更多内容  
buffer.put((byte)10);  

 与java的StringBuffer类似,当setAutoExpand设置为true的时候,内容的长度超过最大长度的时候,会自动翻倍扩展。

 

 

3.IoBuffer的长度改变:

 

 

IoBuffer buffer = IoBuffer.allocate(16);  
buffer.setAutoShrink(true);  
buffer.put((byte)1);  
System.out.println("Initial Buffer capacity = "+buffer.capacity());  
buffer.shrink();  
System.out.println("Initial Buffer capacity after shrink = "+buffer.capacity());  
  
buffer.capacity(32);  
System.out.println("Buffer capacity after incrementing capacity to 32 = "+buffer.capacity());  
buffer.shrink();  
System.out.println("Buffer capacity after shrink= "+buffer.capacity());  

 

(1)capacity():无参可以获取到当前buffer的内容长度。

(2)capacity(32):可以设置buffer的长度。

(3)shrink():可以释放没有被占用的长度。

 

 

 

4.IoBuffer的内存管理分配:

IoBufferAllocater专门Buffer的分配和管理。实现IoBufferAllocater接口后可控制Buffer的分配管理。Mina的以下类实现了IoBufferAllocater接口:

SimpleBufferAllocator(默认)- 任何时间创建一个新的Buffer

CachedBufferAllocator - 当buffer需要复用时缓存buffer

 

 

5.其它有用方法:

static IoBuffer wrap(ByteBuffer nioBuffer):传入 是NIObuffer返回的是IoBuffer。

 

还有很多方法都在子类里面进行实现的,只能在用的过程中归纳那些比较重要了

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics