mina学习笔记(1)

Apache mina是建立在Java NIO上的一个网络应用框架,帮助我们方便的开发高性能的弹性网络应用程序。它提供了抽象的事件驱动异步API,这些功能基于多种网络传输,如TCP/IP,UDP/IP等。因此mina经常被叫做:NIO框架库;客户/服务器框架库;网络socket库。

呵呵,以上是翻译mina官网http://mina.apache.org/的首段话。最近接触,又有时间详细学习之,遂边学边记录下来。

快速入门例子http://mina.apache.org/quick-start-guide.html还是蛮不错的。其中教程中没有提到的是,注意编写一个log4j.properties的配置文件放到工程根目录下,这样才能正确运行。文件可如下编写:

log4j.rootLogger=INFO,CONSOLE
log4j.addivity.org.apache=true
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=INFO
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

 

例子中涉及到的函数有:

一、ByteBuffer

org.apache.mina.common
Class ByteBuffer

java.lang.Object
  extended by org.apache.mina.common.ByteBuffer
All Implemented Interfaces:
Comparable< ByteBuffer>
Direct Known Subclasses:
ByteBufferProxy

public abstract class ByteBuffer
      
       extends 
       Object
      
      
       implements 
       Comparable<
       ByteBuffer>
      
 

A byte buffer used by MINA applications.

This is a replacement for ByteBuffer. Please refer to ByteBuffer and Buffer documentation for usage. MINA does not use 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:

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:

You can change the allocator by calling setAllocator(ByteBufferAllocator).
二、SocketAcceptor

org.apache.mina.transport.socket.nio
Class SocketAcceptor

java.lang.Object
  extended by org.apache.mina.common.support.BaseIoService
      extended by org.apache.mina.common.support.BaseIoAcceptor
          extended by org.apache.mina.transport.socket.nio.SocketAcceptor
All Implemented Interfaces:
IoAcceptor, IoService

public class SocketAcceptor
      
       extends org.apache.mina.common.support.BaseIoAcceptor
      
 

IoAcceptor for socket transport (TCP/IP).

 

 

Version:
$Rev: 389042 $, $Date: 2006-03-27 07:49:41Z $
Author:
The Apache Directory Project (mina-dev@directory.apache.org)

Constructor Summary
SocketAcceptor()
          Create an acceptor with a single processing thread using a NewThreadExecutor
SocketAcceptor(int processorCount, Executor executor)
          Create an acceptor with the desired number of processing threads
 
Method Summary
 voidbind(SocketAddress address, IoHandler handler, IoServiceConfig config)
          Binds to the specified address and handles incoming connections with the specified handler.
 SocketAcceptorConfiggetDefaultConfig()
          Returns the default configuration which is used when you didn't specify any configuration.
 voidsetDefaultConfig(SocketAcceptorConfig defaultConfig)
          Sets the config this acceptor will use by default.
 voidunbind(SocketAddress address)
          Unbinds from the specified address and disconnects all clients connected there.
 voidunbindAll()
          Unbinds all addresses which were bound by this acceptor.
 
Methods inherited from class org.apache.mina.common.support.BaseIoAcceptor
bind, newSession
 
Methods inherited from class org.apache.mina.common.support.BaseIoService
addListener, getFilterChain, getFilterChainBuilder, getListeners, getManagedServiceAddresses, getManagedSessions, isManaged, removeListener, setFilterChainBuilder
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.apache.mina.common.IoService
addListener, getFilterChain, getFilterChainBuilder, getManagedServiceAddresses, getManagedSessions, isManaged, removeListener, setFilterChainBuilder

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值