Apache Mina入門

Mina第一次聽到這個名稱的時候,我覺得是個MM的名字米娜,後來才知道…html

Apache MINA(Multipurpose Infrastructure for Network Applications)java

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

是 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服務端session

 

/**框架

 *socket

 */tcp

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

相關文章
相關標籤/搜索