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

 

Apache Mina是一个用于开发高性能、高可扩展性网络应用程序的Java框架。它提供了一种简单和灵活的方式来构建基于TCP/IP和UDP/IP协议的客户端和服务器端应用。 在学习Apache Mina时,首先需要了解它的基本概念和架构。Mina采用了NIO(非阻塞IO)的方式来实现网络通信。它的核心组件是IoService,它负责接收客户端的连接请求,并将请求分发给对应的I/O处理器进行处理。而I/O处理器则负责实际的数据读写和业务逻辑的处理。 在使用Mina进行开发时,我们首先需要创建一个IoAcceptor对象来监听指定的端口,并设置相应的处理器。当有客户端发起连接请求时,IoAcceptor会接收并处理这些请求。同时,我们还需要编写相应的I/O处理器来对接收到的数据进行处理和响应。 Mina还提供了一些便捷的工具类和接口,以简化开发过程。例如,可以使用IoBuffer来处理数据的读写,它类似于Java NIO中的ByteBuffer。同时,Mina还提供了一些过滤器,可以在数据传输的过程中进行一些常用的操作,比如加密、压缩、编解码等。 值得一提的是,Mina支持多种编解码协议,包括自定义的协议。它可以根据指定的编解码规则将数据进行解析和组装。这在实际应用中非常实用,因为经常会遇到需要对传输的数据进行编码和解码的情况。 总的来说,学习Apache Mina需要了解其基本概念、架构和核心组件,并掌握基本的开发流程和常用的工具类和接口。通过学习Mina,我们可以更加方便地开发出高性能、高可扩展性的网络应用程序。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值