Apache Mina入门

jopen 11年前

Apache MINA(Multipurpose Infrastructure for Network Applications)

官网http://mina.apache.org/

是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络应用程序提供了非常便利的框架。当前发行的 MINA 版本支持基于 Java NIO 技术的 TCP/UDP 应用程序开发、串口通讯程序(只在最新的预览版中提供),MINA 所支持的功能也在进一步的扩展中。   目前正在使用 MINA 的软件包括有:Apache Directory Project、AsyncWeb、AMQP(Advanced Message Queuing Protocol)、RED5 Server(Macromedia Flash Media RTMP)、ObjectRADIUS、Openfire 等等。

本文就介绍入门mina的入门,

参考文档http://mina.apache.org/mina-project/quick-start-guide.html

第一步、定义MinaTimeServer.java mina服务端

 

/**     *     */    package com.figo.onlineshop.test;         import java.io.IOException;    import java.net.InetSocketAddress;    import java.nio.charset.Charset;         import org.apache.mina.core.service.IoAcceptor;    import org.apache.mina.core.session.IdleStatus;    import org.apache.mina.filter.codec.ProtocolCodecFilter;    import org.apache.mina.filter.codec.textline.TextLineCodecFactory;    import org.apache.mina.filter.logging.LoggingFilter;    import org.apache.mina.transport.socket.nio.NioSocketAcceptor;         /**     * @author zhuzhifei     *     */    public class MinaTimeServer {        private static final int PORT = 9123;                   /**               * @param args               */              public static void main(String[] args) {                       // TODO Auto-generated method stub                       //定义socket接收器                       IoAcceptor acceptor = new NioSocketAcceptor();            //添加日志记录            acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );            //添加编码解码器            acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));            //添加处理器(用于接收数据后处理处理数据逻辑)            acceptor.setHandler(  new TimeServerHandler() );            //设置读取数据缓存单位byte            acceptor.getSessionConfig().setReadBufferSize( 2048 );            //设置多长时间后接收器开始空闲            acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );                 try {                      //绑定某个端口,作为数据入口                                acceptor.bind( new InetSocketAddress(PORT) );                       } catch (IOException e) {                                // TODO Auto-generated catch block                                e.printStackTrace();                       }                        }         }     

第二步、定义消息处理器TimeServerHandler.java

/**     *     */    package com.figo.onlineshop.test;         import java.util.Date;         import org.apache.mina.core.service.IoHandlerAdapter;    import org.apache.mina.core.session.IdleStatus;    import org.apache.mina.core.session.IoSession;    import org.slf4j.Logger;    import org.slf4j.LoggerFactory;         /**     * @author zhuzhifei     *     */    //必须继承IoHandlerAdapter    public class TimeServerHandler extends IoHandlerAdapter {        private final Logger logger = LoggerFactory.getLogger(MinaTimeServer.class);        //补抓异常              @Override              public void exceptionCaught(IoSession session, Throwable cause)                                throws Exception {                       // TODO Auto-generated method stub                       super.exceptionCaught(session, cause);              }        //获取客户端消息后处理逻辑              @Override              public void messageReceived(IoSession session, Object message)                                 throws Exception {                       // TODO Auto-generated method stub                       super.messageReceived(session, message);                       String str = message.toString();            if( str.trim().equalsIgnoreCase("quit") ) {                session.close(true);                return;            }                 Date date = new Date();            session.write( "current time:"+date.toString() );//该消息将返回给客户端            System.out.println("Message Received:"+str);            logger.info(date.toString()+"Message Received:"+str);//日志没有输出why?                   }        //发送消息              @Override              public void messageSent(IoSession session, Object message) throws Exception {                       // TODO Auto-generated method stub                       super.messageSent(session, message);              }        //当前会话关闭              @Override              public void sessionClosed(IoSession session) throws Exception {                       // TODO Auto-generated method stub                       super.sessionClosed(session);              }        //创建会话              @Override              public void sessionCreated(IoSession session) throws Exception {                       // TODO Auto-generated method stub                       super.sessionCreated(session);              }        //会话空闲              @Override              public void sessionIdle(IoSession session, IdleStatus status)                                throws Exception {                       // TODO Auto-generated method stub                       super.sessionIdle(session, status);                       System.out.println( "IDLE " + session.getIdleCount( status ));              }        //打开会话              @Override              public void sessionOpened(IoSession session) throws Exception {                       // TODO Auto-generated method stub                       super.sessionOpened(session);              }         }

第三步、模拟客户端tcp调用

MinaTimeServer.java run as java Application后

C:\Documents and Settings\zhuzhifei>telnet 127.0.0.1 9123 连上服务器

客户端输入:abc后

服务端接收到:

2012-12-25 18:26:52 INFO  com.figo.onlineshop.test.MinaTimeServer - Tue Dec 25 18:26:52 CST 2012Message Received:abc

客户端显示:current time:Tue Dec 25 18:26:52 CST 2012