org.apache.mina.common.ByteBuffer类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(13.1k)|赞(0)|评价(0)|浏览(198)

本文整理了Java中org.apache.mina.common.ByteBuffer类的一些代码示例,展示了ByteBuffer类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ByteBuffer类的具体详情如下:
包路径:org.apache.mina.common.ByteBuffer
类名称:ByteBuffer

ByteBuffer介绍

[英]A byte buffer used by MINA applications.

This is a replacement for java.nio.ByteBuffer. Please refer to java.nio.ByteBuffer and java.nio.Buffer documentation for usage. MINA does not use NIO java.nio.ByteBuffer directly for two reasons:

  • It doesn't provide useful getters and putters such as fill, get/putString, and get/putAsciiInt() enough.
  • It is hard to distinguish if the buffer is created from MINA buffer pool or not. MINA have to return used buffers back to pool.
  • It is difficult to write variable-length data due to its fixed capacity

Allocation

You can get a heap buffer from buffer pool:

ByteBuffer buf = ByteBuffer.allocate(1024, false);

you can also get a direct buffer from buffer pool:

ByteBuffer buf = ByteBuffer.allocate(1024, true);

or you can let MINA choose:

ByteBuffer buf = ByteBuffer.allocate(1024);

Acquire/Release

Please note that you never need to release the allocated buffer because MINA will release it automatically when:

  • You pass the buffer by calling IoSession#write(Object).
  • You pass the buffer by calling IoFilter.NextFilter#filterWrite(IoSession,IoFilter.WriteRequest).
  • You pass the buffer by calling ProtocolEncoderOutput#write(ByteBuffer).
    And, you don't need to release any ByteBuffer which is passed as a parameter of IoHandler#messageReceived(IoSession,Object) method. They are released automatically when the method returns.

You have to release buffers manually by calling #release() when:

  • You allocated a buffer, but didn't pass the buffer to any of two methods above.
  • You called #acquire() to prevent the buffer from being released.

Wrapping existing NIO buffers and arrays

This class provides a few wrap(...) methods that wraps any NIO buffers and byte arrays. Wrapped MINA buffers are not returned to the buffer pool by default to prevent unexpected memory leakage by default. In case you want to make it pooled, you can call #setPooled(boolean)with true flag to enable pooling.

AutoExpand

Writing variable-length data using NIO ByteBuffers is not really easy, and it is because its size is fixed. MINA ByteBuffer introduces autoExpand property. If autoExpand property is true, you never get BufferOverflowException or IndexOutOfBoundsException (except when index is negative). It automatically expands its capacity and limit value. For example:

String greeting = messageBundle.getMessage( "hello" ); 
ByteBuffer buf = ByteBuffer.allocate( 16 ); 
// Turn on autoExpand (it is off by default) 
buf.setAutoExpand( true ); 
buf.putString( greeting, utf8encoder );

NIO ByteBuffer is reallocated by MINA ByteBuffer behind the scene if the encoded data is larger than 16 bytes. Its capacity will increase by two times, and its limit will increase to the last position the string is written.

Derived Buffers

Derived buffers are the buffers which were created by #duplicate(), #slice(), or #asReadOnlyBuffer(). They are useful especially when you broadcast the same messages to multiple IoSessions. Please note that the derived buffers are neither pooled nor auto-expandable. Trying to expand a derived buffer will raise IllegalStateException.

Changing Buffer Allocation and Management Policy

MINA provides a ByteBufferAllocator interface to let you override the default buffer management behavior. There are two allocators provided out-of-the-box:

  • PooledByteBufferAllocator (Default)
  • SimpleByteBufferAllocator
    You can change the allocator by calling #setAllocator(ByteBufferAllocator).
    [中]MINA应用程序使用的字节缓冲区。
    这是java的替代品。尼奥。拜特伯弗。请参考java。尼奥。ByteBuffer和java。尼奥。缓冲区文档的使用。MINA不使用NIO java。尼奥。直接使用ByteBuffer有两个原因:
    *它没有提供足够有用的getter和putter,例如fillget/putStringget/putAsciiInt()
    *很难区分缓冲区是否是从MINA缓冲池创建的。MINA必须将使用过的缓冲区返回池中。
    *由于可变长度数据的容量固定,因此很难写入可变长度数据
    分配
    您可以从缓冲池中获取堆缓冲区:
    <
ByteBuffer buf = ByteBuffer.allocate(1024, false);

您也可以从缓冲池获得直接缓冲:<

ByteBuffer buf = ByteBuffer.allocate(1024, true);

或者您可以让MINA选择:<<

ByteBuffer buf = ByteBuffer.allocate(1024);

获取/发布
请注意,您永远不需要释放分配的缓冲区,因为MINA将在以下情况下自动释放它:
*通过调用IoSession#write(Object)来传递缓冲区。
*通过调用IoFilter传递缓冲区。NextFilter#filterWrite(IoSession,IoFilter.WriterRequest)。
*通过调用ProtocolEncoderOutput#write(ByteBuffer)传递缓冲区。
而且,您不需要释放任何作为IoHandler#messageReceived(IoSession,Object)方法参数传递的ByteBuffer。当方法返回时,它们会自动释放。
在以下情况下,必须通过调用#release()手动释放缓冲区:
*您分配了一个缓冲区,但没有将缓冲区传递给上述两种方法中的任何一种。
*您调用了#acquire()以防止释放缓冲区。
包装现有NIO缓冲区和阵列
此类提供了一些换行(…)方法包装任何NIO缓冲区和字节数组。默认情况下,包装的MINA缓冲区不会返回到缓冲池,以防止意外的内存泄漏。如果要使其成为池,可以使用true标志调用#setPooled(布尔值)以启用池。
自动扩展
使用NIO ByteBuffers编写可变长度数据并不容易,因为它的大小是固定的。MINA ByteBuffer引入了自动扩展属性。若autoExpand属性为true,则永远不会获得BufferOverflowException或IndexOutOfBoundsException(索引为负时除外)。它会自动扩展其容量和限制值。例如:

String greeting = messageBundle.getMessage( "hello" ); 
ByteBuffer buf = ByteBuffer.allocate( 16 ); 
// Turn on autoExpand (it is off by default) 
buf.setAutoExpand( true ); 
buf.putString( greeting, utf8encoder );

如果编码数据大于16字节,则NIO ByteBuffer将由MINA ByteBuffer在幕后重新分配。其容量将增加两倍,其限制将增加到写入字符串的最后位置。
派生缓冲区
派生缓冲区是由#duplicate()、#slice()或#asReadOnlyBuffer()创建的缓冲区。它们非常有用,尤其是当您向多个会话广播相同的消息时。请注意,派生缓冲区既不是池也不是自动扩展的。尝试扩展派生缓冲区将引发IllegalStateException。
更改缓冲区分配和管理策略
MINA提供了一个ByteBufferAllocator接口,允许您覆盖默认的缓冲区管理行为。有两个现成的分配器:
*PooledByteBufferAllocator(默认)
*SimpleByteBufferAllocator
您可以通过调用#setAllocator(ByteBufferAllocator)来更改分配器。

代码示例

代码示例来源:origin: apache/incubator-dubbo

@Override
public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception {
  int readable = in.limit();
  if (readable <= 0) {
    return;
      buffer.writeBytes(in.buf());
      frame = buffer;
    } else {
      int size = buffer.readableBytes() + in.remaining();
      frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize);
      frame.writeBytes(buffer, buffer.readableBytes());
      frame.writeBytes(in.buf());
    frame = ChannelBuffers.wrappedBuffer(in.buf());

代码示例来源:origin: apache/incubator-dubbo

@Override
  public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024);
    MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler);
    try {
      codec.encode(channel, buffer, msg);
    } finally {
      MinaChannel.removeChannelIfDisconnected(session);
    }
    out.write(ByteBuffer.wrap(buffer.toByteBuffer()));
    out.flush();
  }
}

代码示例来源:origin: org.apache.directory.mina/mina-core

private void readSession( DatagramSessionImpl session )
{
  ByteBuffer readBuf = ByteBuffer.allocate( session.getReadBufferSize() );
  try
  {
    int readBytes = session.getChannel().read( readBuf.buf() );
    if( readBytes > 0 )
    {
      readBuf.flip();
      ByteBuffer newBuf = ByteBuffer.allocate( readBuf.limit() );
      newBuf.put( readBuf );
      newBuf.flip();
      session.increaseReadBytes( readBytes );
      ( ( DatagramFilterChain ) session.getFilterChain() ).messageReceived( session, newBuf );
    }
  }
  catch( IOException e )
  {
    ( ( DatagramFilterChain ) session.getFilterChain() ).exceptionCaught( session, e );
  }
  finally
  {
    readBuf.release();
  }
}

代码示例来源:origin: org.apache.directory.mina/mina-core

ByteBuffer tmp = ByteBuffer.allocate( 2 ).setAutoExpand( true );
  tmp.putString( delimiter.getValue(), charset.newEncoder() );
  tmp.flip();
  delimBuf = tmp;
int oldPos = in.position();
int oldLimit = in.limit();
while( in.hasRemaining() )
  byte b = in.get();
  if( delimBuf.get( matchCount ) == b )
    if( matchCount == delimBuf.limit() )
      int pos = in.position();
      in.limit( pos - matchCount + oldMatchCount );
      in.position( oldPos );
      buf.put( in );
      if( buf.position() > maxLineLength )
        throw new BufferDataException( "Line is too long: " + buf.position() );
      buf.flip();
      out.write( buf.getString( decoder ) );
      buf.clear();
      in.limit( oldLimit );
      in.position( pos );

代码示例来源:origin: org.reddwarfserver.client/sgs-client

private void processReceiveBuffer(FilterListener listener) {
  if (msgBuf.remaining() > MAX_BUFFER_SIZE) {
    logger.log(Level.WARNING,
      "Recv filter buffer is larger than expected: {0,number,#}",
      msgBuf.remaining());
  while (msgBuf.hasRemaining()) {
    if (msgBuf.remaining() < 2) {
      break;
    if (!msgBuf.prefixedDataAvailable(2)) {
      break;
    int msgLen = msgBuf.getShort() & 0xFFFF;
      msgBuf.slice().asReadOnlyBuffer().limit(msgLen);
    msgBuf.skip(msgLen);
  msgBuf.compact();
      msgBuf.position());

代码示例来源:origin: org.apache.directory.mina/mina-core

public boolean equals( Object o )
{
  if( !( o instanceof ByteBuffer ) )
  {
    return false;
  }
  ByteBuffer that = (ByteBuffer)o;
  if( this.remaining() != that.remaining() )
  {
    return false;
  }
  int p = this.position();
  for( int i = this.limit() - 1, j = that.limit() - 1; i >= p; i --, j -- )
  {
    byte v1 = this.get( i );
    byte v2 = that.get( j );
    if( v1 != v2 )
    {
      return false;
    }
  }
  return true;
}

代码示例来源:origin: org.apache.directory.mina/mina-core

int oldPos = in.position();
int oldLimit = in.limit();
while( in.hasRemaining() )
  byte b = in.get();
  boolean matched = false;
  switch( b )
    int pos = in.position();
    in.limit( pos - matchCount + oldMatchCount );
    in.position( oldPos );
    buf.put( in );
    if( buf.position() > maxLineLength )
      throw new BufferDataException( "Line is too long: " + buf.position() );
    buf.flip();
    out.write( buf.getString( decoder ) );
    buf.clear();
    in.limit( oldLimit );
    in.position( pos );
    oldPos = pos;
    matchCount = 0;
in.position( oldPos );
in.limit( in.limit() - matchCount + oldMatchCount );
buf.put( in );

代码示例来源:origin: org.apache.directory.server/mitosis

public final void encode( IoSession session, Object in, ProtocolEncoderOutput out ) throws Exception
{
  BaseMessage m = ( BaseMessage ) in;
  ByteBuffer buf = ByteBuffer.allocate( 16 );
  buf.setAutoExpand( true );
  buf.put( ( byte ) m.getType() );
  buf.putInt( m.getSequence() );
  buf.putInt( 0 ); // placeholder for body length field
  final int bodyStartPos = buf.position();
  encodeBody( m, buf );
  final int bodyEndPos = buf.position();
  final int bodyLength = bodyEndPos - bodyStartPos;
  // fill bodyLength
  buf.position( bodyStartPos - 4 );
  buf.putInt( bodyLength );
  buf.position( bodyEndPos );
  buf.flip();
  out.write( buf );
}

代码示例来源:origin: org.apache.directory.mina/mina-core

sum += ( ( ByteBuffer ) bufferQueue.get( i ) ).remaining();
ByteBuffer newBuf = ByteBuffer.allocate( sum );
  newBuf.put( buf );
  buf.release();
newBuf.flip();
bufferQueue.push(newBuf);

代码示例来源:origin: org.apache.directory.mina/mina-core

rb.mark();
byteCount = rb.remaining();
ByteBuffer wb = ByteBuffer.allocate( rb.remaining() );
wb.put( rb );
wb.flip();
rb.reset();
messageCopy = wb;

代码示例来源:origin: org.apache.directory.mina/mina-core

private void storeRemainingInSession(ByteBuffer buf, IoSession session)
  {
    ByteBuffer remainingBuf = ByteBuffer.allocate( buf.remaining() );
    remainingBuf.setAutoExpand( true );
    remainingBuf.put( buf );
    session.setAttribute( BUFFER, remainingBuf );
  }    
}

代码示例来源:origin: org.reddwarfserver.client/sgs-client

/**
 * Processes network data of arbitrary length and dispatches zero or
 * more complete messages to the given {@code listener}.  If a partial
 * message remains, it is buffered until more data is received.
 *
 * @param listener the {@code FilterListener} to receive complete messages
 * @param buf the data to filter and optionally deliver to the
 *        {@code FilterListener}
 */
void filterReceive(FilterListener listener, ByteBuffer buf) {
  logger.log(Level.FINEST,
    "processing {0,number,#} bytes",
    buf.remaining());
  // Append the new data to the buffer
  msgBuf.expand(buf.remaining());
  msgBuf.put(buf);
  msgBuf.flip();
  processReceiveBuffer(listener);
}

代码示例来源:origin: org.apache.directory.mina/mina-core

public int read( byte[] b, int off, int len )
{
  int remaining = ByteBuffer.this.remaining();
  if( remaining > 0 )
  {
    int readBytes = Math.min( remaining, len );
    ByteBuffer.this.get( b, off, readBytes );
    return readBytes;
  }
  else
  {
    return -1;
  }
}

代码示例来源:origin: org.apache.mina/mina-filter-ssl

/**
 * Creates a new Mina byte buffer that is a deep copy of the remaining bytes
 * in the given buffer (between index buf.position() and buf.limit())
 *
 * @param src the buffer to copy
 * @return the new buffer, ready to read from
 */
public static org.apache.mina.common.ByteBuffer copy(java.nio.ByteBuffer src) {
  org.apache.mina.common.ByteBuffer copy = org.apache.mina.common.ByteBuffer
      .allocate(src.remaining());
  copy.put(src);
  copy.flip();
  return copy;
}

代码示例来源:origin: org.apache.directory.mina/mina-core

public int compareTo( Object o )
{
  ByteBuffer that = (ByteBuffer)o;
  int n = this.position() + Math.min( this.remaining(), that.remaining() );
  for( int i = this.position(), j = that.position(); i < n; i ++, j ++ )
  {
    byte v1 = this.get( i );
    byte v2 = that.get( j );
    if( v1 == v2 )
    {
      continue;
    }
    if( v1 < v2 )
    {
      return -1;
    }
    return +1;
  }
  return this.remaining() - that.remaining();
}

代码示例来源:origin: org.apache.directory.mina/mina-core

public void encode( IoSession session, Object message, ProtocolEncoderOutput out ) throws Exception
  {
    if( !( message instanceof Serializable ) )
    {
      throw new NotSerializableException();
    }

    ByteBuffer buf = ByteBuffer.allocate( 64 );
    buf.setAutoExpand( true );
    buf.putObject( message );
    
    int objectSize = buf.position() - 4;
    if( objectSize > maxObjectSize )
    {
      buf.release();
      throw new IllegalArgumentException( "The encoded object is too big: " + objectSize + " (> " + maxObjectSize + ')' );
    }
    
    buf.flip();
    out.write( buf );
  }
}

代码示例来源:origin: org.apache.directory.mina/mina-core

public int hashCode()
{
  int h = 1;
  int p = position();
  for( int i = limit() - 1; i >= p; i -- )
  {
    h = 31 * h + get( i );
  }
  return h;
}

代码示例来源:origin: org.apache.directory.mina/mina-core

private void read( SocketSessionImpl session )
  ByteBuffer buf = ByteBuffer.allocate( session.getReadBufferSize() );
  SocketChannel ch = session.getChannel();
    buf.clear();
      while( ( ret = ch.read( buf.buf() ) ) > 0 )
      buf.flip();
      buf.release();

代码示例来源:origin: org.apache.directory.mina/mina-core

if( buf.remaining() == 0 )
  buf.reset();
  ( ( SocketFilterChain ) session.getFilterChain() ).messageSent( session, req );
  continue;
int writtenBytes = ch.write( buf.buf() );
if( writtenBytes > 0 )
if( buf.hasRemaining() )

代码示例来源:origin: org.apache.directory.mina/mina-core

public void encode( IoSession session, Object message,
          ProtocolEncoderOutput out )
    throws Exception
{
  CharsetEncoder encoder = ( CharsetEncoder ) session.getAttribute( ENCODER );
  if( encoder == null )
  {
    encoder = charset.newEncoder();
    session.setAttribute( ENCODER, encoder );
  }
  
  String value = message.toString();
  ByteBuffer buf = ByteBuffer.allocate( value.length() ).setAutoExpand( true );
  buf.putString( value, encoder );
  if( buf.position() > maxLineLength )
  {
    throw new IllegalArgumentException( "Line length: " + buf.position() );
  }
  buf.putString( delimiter.getValue(), encoder );
  buf.flip();
  out.write( buf );
}

相关文章