mina简单理解

来源:互联网 发布:dbcc修复数据库 编辑:程序博客网 时间:2024/05/19 13:24

引用官方文档:

Apache MINA is a network application framework which helps users develop high performance and high scalability network applications easily. It provides an abstract ·event-driven · asynchronous API over various transports such as TCP/IP and UDP/IP via Java NIO.

Apache MINA is often called:

  • NIO framework · library,
  • client · server framework · library, or
  • a networking · socket library.

Apache MINA(AMulti-purpose Infrastructure forNetwork Applications)是一个网络应用框架,它能帮助用户很容易地开发高性能、高收缩性的网络应用。

Introduction

This tutorial will walk you through the process of building a MINA based program.  This tutorial will walk through building a time server.  The following prerequisites are required for this tutorial:

  • MINA 1.1 Core
  • JDK 1.5 or greater
  • SLF4J 1.3.0 or greater
    • Log4J 1.2 users: slf4j-api.jarslf4j-log4j12.jar, and Log4J 1.2.x
    • Log4J 1.3 users: slf4j-api.jarslf4j-log4j13.jar, and Log4J 1.3.x
    • java.util.logging users: slf4j-api.jar and slf4j-jdk14.jar
    • IMPORTANT: Please make sure you are using the right slf4j-*.jar that matches to your logging framework.\
      For instance, slf4j-log4j12.jar and log4j-1.3.x.jar can not be used together, and will malfunction.

I have tested this program on both Windows© 2000 professional and linux.  If you have any problems getting this program to work, please do not hesitate to contact us in order to talk to the MINA developers.  Also, this tutorial has tried to remain independent of development environments (IDE, editors..etc).  This tutorial will work with any environment that you are comfortable with.  Compilation commands and steps to execute the program have been removed for brevity.  If you need help learning how to either compile of execute java programs, please consult the Java tutorial.

Writing the MINA time server 

 We will begin by creating a file called MinaTimeServer.java.  The initial code can be found below:

public class MinaTimeServer {    public static void main(String[] args) {    // code will go here next    }}

This code should be straightforward to all.  We are simply defining a main method that will be used to kick off the program.  At this point, we will begin to add the code that will make up our server.  First off, we need an object that will be used to listen for incoming connections.  Since this program will be TCP/IP based, we will add a SocketAcceptor to our program.

import org.apache.mina.common.ByteBuffer;import org.apache.mina.common.IoAcceptor;import org.apache.mina.common.SimpleByteBufferAllocator;import org.apache.mina.transport.socket.nio.SocketAcceptor;public class MinaTimeServer {    public static void main(String[] args) {        // The following two lines change the default buffer type to 'heap',        // which yields better performance.c        ByteBuffer.setUseDirectBuffers(false);        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());        IoAcceptor acceptor = new SocketAcceptor();    }}

1.服务端创建一个监听器

With the SocketAcceptor class in place, we can go ahead and define the handler class and bind the SocketAcceptor to a port. If you are interested in adding a thread model to the SocketAcceptor, please read the Configuring Thread Model tutorial.
We will now add in the SocketAcceptor configuration. This will allow us to make socket-specific settings for the socket that will be used to accept connections from clients.

import java.io.IOException;import java.nio.charset.Charset;import org.apache.mina.common.ByteBuffer;import org.apache.mina.common.IoAcceptor;import org.apache.mina.common.SimpleByteBufferAllocator;import org.apache.mina.filter.LoggingFilter;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.transport.socket.nio.SocketAcceptor;import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;public class MinaTimeServer {    private static final int PORT = 9123;    public static void main(String[] args) throws IOException {        ByteBuffer.setUseDirectBuffers(false);        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());        IoAcceptor acceptor = new SocketAcceptor();        SocketAcceptorConfig cfg = new SocketAcceptorConfig();        cfg.getFilterChain().addLast( "logger", new LoggingFilter() );        cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));    }}

2.过滤链中添加过滤器,过滤器对数据流进行操作,并传递能下一下过滤器,协议解析就是在这儿进行的如

cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));


Here was have created a new instance of the SocketAcceptorConfig class that will be used to pass in to the acceptor once we are ready to start up the acceptor. First, we have set the reuse address flag. See more information about this in the JDK Documentation. Next we add a filter to the configuration. This filter will log all information such as newly created sessions, messages received, messages sent, session closed. The next filter is a ProtocolCodecFilter. This filter will translate binary or protocol specific data into message object and vice versa.

This last addition will bind the acceptor to the port. This method will signal the startup of the server process. Without this method call, the server will not service client connections.

import java.io.IOException;import java.net.InetSocketAddress;import java.nio.charset.Charset;import org.apache.mina.common.ByteBuffer;import org.apache.mina.common.IoAcceptor;import org.apache.mina.common.SimpleByteBufferAllocator;import org.apache.mina.filter.LoggingFilter;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.transport.socket.nio.SocketAcceptor;import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;public class MinaTimeServer {    private static final int PORT = 9123;    public static void main(String[] args) throws IOException {        ByteBuffer.setUseDirectBuffers(false);        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());        IoAcceptor acceptor = new SocketAcceptor();        SocketAcceptorConfig cfg = new SocketAcceptorConfig();        cfg.getFilterChain().addLast( "logger", new LoggingFilter() );        cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));        acceptor.bind( new InetSocketAddress(PORT), new TimeServerHandler(), cfg);        System.out.println("MINA Time server started.");    }}

3.绑定端口并启动监听

What you see here is that we have defined a variable port of type integer and made a call to SocketAcceptor.bind(SocketAddress,IoHandler).  The first parameter is the SocketAddress that describes the network address that will be listening on, in this case port 9123, and the local address. 

The second parameter passed to the bind method is a class that must implement the interface IoHandler.  For almost all programs that use MINA, this becomes the workhorse of the program, as it services all incoming requests from the clients.  For this tutorial, we will extend the class IoHandlerAdapter.  This is a class that follows the adapter design pattern which simplifies the amount of code that needs to be written in order to satisfy the requirement of passing in a class that implements the IoHandler interface. 

The third parameter is the configuration object, cfg, which has been configured with a logger filter and a codec filter.  MINA is set up such that each message that is received will be passed through any and all filters in the filter chain defined for the IoAcceptor.  In this case, we will pass all messages through a logging filter and then a codec filter.  The logging filter will simply log the message using the SL4J library, and the codec filter will decode each message received and encode each message sent using the supplied TextLineCodecFactory class.   

4.设置ioHandler ,逻辑处理在些进行

Below is the class TimeServerHandler:

import java.util.Date;import org.apache.mina.common.IdleStatus;import org.apache.mina.common.IoHandlerAdapter;import org.apache.mina.common.IoSession;import org.apache.mina.common.TransportType;import org.apache.mina.transport.socket.nio.SocketSessionConfig;public class TimeServerHandler extends IoHandlerAdapter {public void exceptionCaught(IoSession session, Throwable t) throws Exception {t.printStackTrace();session.close();}public void messageReceived(IoSession session, Object msg) throws Exception {String str = msg.toString();if( str.trim().equalsIgnoreCase("quit") ) {session.close();return;}Date date = new Date();session.write( date.toString() );System.out.println("Message written...");}public void sessionCreated(IoSession session) throws Exception {System.out.println("Session created...");if( session.getTransportType() == TransportType.SOCKET )((SocketSessionConfig) session.getConfig() ).setReceiveBufferSize( 2048 );        session.setIdleTime( IdleStatus.BOTH_IDLE, 10 );}}



import java.io.IOException;import java.net.InetSocketAddress;import java.nio.charset.Charset;import org.apache.mina.common.ByteBuffer;import org.apache.mina.common.IoAcceptor;import org.apache.mina.common.SimpleByteBufferAllocator;import org.apache.mina.filter.LoggingFilter;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.transport.socket.nio.SocketAcceptor;import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;public class MinaTimeServer {    private static final int PORT = 9123;    public static void main(String[] args) throws IOException {        ByteBuffer.setUseDirectBuffers(false);        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());        IoAcceptor acceptor = new SocketAcceptor();        SocketAcceptorConfig cfg = new SocketAcceptorConfig();        cfg.getFilterChain().addLast( "logger", new LoggingFilter() );        cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));        IohanderAdaptor handler = new IoHandlerAdaptor();        acceptor.setHander(handler;        acceptor.bind( new InetSocketAddress(PORT), new TimeServerHandler(), cfg);        System.out.println("MINA Time server started.");    }}


The exceptionCaught method will simply print the stack trace of the error and close the session.  For most programs, this will be standard practice unless the handler can recover from the exception condition.

The messageReceived method will receive the data from the client and write back to the client the current time.  If the message received from the client is the word "quit", then the session will be closed.  This method will also print out the current time to the client.  Depending on the protocol codec that you use, the object (second parameter) that gets passed in to this method will be different, as well as the object that you pass in to the session.write(Object) method.  If you do not specify a protocol codec, you will most likely receive a ByteBuffer object, and be required to write out a ByteBuffer object.

The sessionCreated method is typically where your session initialization occurs.  In this case, we print out that the method has been entered, and then test if the transport type of the sesion is socket based (versus UDP), and then set the receive buffer size.  In the case above, the incoming buffer size is set to 2048 bytes.  The idle time is also set to 10 seconds.  If we were to override the sessionIdle method, the sessionIdle method would get called every 10 seconds.


再看看整个处理过程



原创粉丝点击