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.addivity.org.apache=true
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 org.apache.mina.common.ByteBuffer
-
All Implemented Interfaces:
- Comparable< ByteBuffer>
-
Direct Known Subclasses:
- ByteBufferProxy
public abstract class ByteBufferextends 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, andget/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).
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:
setAllocator(ByteBufferAllocator).
二、SocketAcceptor
org.apache.mina.transport.socket.nio
Class SocketAcceptor
java.lang.Object org.apache.mina.common.support.BaseIoService org.apache.mina.common.support.BaseIoAcceptor org.apache.mina.transport.socket.nio.SocketAcceptor
-
All Implemented Interfaces:
- IoAcceptor, IoService
public class SocketAcceptorextends 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 ======== --><!-- -->
| Constructor Summary | |
|---|---|
SocketAcceptor() Create an acceptor with a single processing thread using a NewThreadExecutor | |
SocketAcceptor(intprocessorCount, Executorexecutor) Create an acceptor with the desired number of processing threads | |
| Method Summary | |
|---|---|
void | bind(SocketAddressaddress, IoHandlerhandler, IoServiceConfigconfig) Binds to the specified address and handles incoming connections with the specified handler. |
SocketAcceptorConfig | getDefaultConfig() Returns the default configuration which is used when you didn't specify any configuration. |
void | setDefaultConfig(SocketAcceptorConfigdefaultConfig) Sets the config this acceptor will use by default. |
void | unbind(SocketAddressaddress) Unbinds from the specified address and disconnects all clients connected there. |
void | unbindAll() 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 |
本文介绍了Apachemina框架的基础知识,包括其作为Java NIO框架的特点与优势,以及如何使用ByteBuffer进行高效的数据处理。此外,还介绍了如何通过SocketAcceptor实现TCP/IP连接的接受与管理。
430

被折叠的 条评论
为什么被折叠?



