Apache MINA 快速入門

來源:互聯網
上載者:User

題記:

因為開發需要用到Apache MINA架構,所以看了一下其文檔,順手譯了一部分,下面內容沒有測試,只是譯了出來,後面測試一下,如果有問題再提出來。

Apache MINA 快速入門

Added by Mark Webb, last edited by Trustin Lee on Apr 16, 2007    (view change)

1    簡介

建立一個基於MINA的時間伺服器,下面的內容需要先準備好。

MINA 1.1 Core
JDK 1.5 or greater
SLF4J    1.3.0 or greater
>>Log4J 1.2 users: slf4j-api.jar, slf4j-log4j12.jar, and Log4J    1.2.x
>>Log4J 1.3 users: slf4j-api.jar, slf4j-log4j13.jar, and Log4J    1.3.x
>>java.util.logging users: slf4j-api.jar and slf4j-jdk14.jar

這個程式只測試了Windows2000pro和Linux系統,並且在做的時候沒有依賴於一些開發平台的環境。

2    編寫MINA時間服務

下面先建立一個檔案MinaTimeServer.java,代碼如下:

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

下面會慢慢將這個類寫完,這裡先定義一個main用於啟動程式。這一步結束後,還需要一個監聽串連的對象,因為這個程式是基於TCP/IP的,這裡將增加一個SocketAcceptor。

import org.apache.mina.common.IoAcceptor;
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.
      ByteBuffer.setUseDirectBuffers(false);
      ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
      IoAcceptor acceptor = new SocketAcceptor();
    }
}

通過這裡的SocketAcceptor類,下面將把它綁定到一個連接埠上,如果你想增加一個執行緒模式到該類的話,參考"配置執行緒模式"部分。

import java.io.IOException;
import java.net.InetSocketAddress;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptor;

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.getSessionConfig().setReuseAddress( true );
      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.");
    }
}

這裡定義了一個整型的連接埠變數,呼叫SocketAcceptor.bind(SocketAddress,IoHandler,cfg),第一個參數是要監聽的網址,是本地的9123連接埠。

第二個參數傳的是實現IoHandler介面的類,是服務於所有的用戶端請求的。在這裡,將會擴充IoHandlerAdapter類,這類遵循"適配器設計模式"的。

第三個參數是設定物件,用於配置日誌和編碼過濾器。每一個資訊都會通過在IoAcceptor中定義的過濾器鏈的所有過濾器。在這風景點,將會將資訊通過日誌和編碼過濾器。日誌過濾器用SL4J庫記錄資訊,而編碼過濾器則反編碼所有收到的資訊,並且將所有TextLineCodecFactory發送的資訊進行編碼。

下面就是TimeServerHandler類的代碼:

import java.util.Date;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;

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 );
    }
}

這裡用於管理資訊,覆蓋了exceptionCaught,messageReceived和sessionCreated方法,如前所示,該類擴充了IoHandlerAdapter。

exceptionCaught方法將會列印錯誤並且關閉對話,對於大多數的情況來講,這是標準的處理方法,除非能從異常中恢複過來。

messageReceived方法將收到從用戶端發來的資料,並且寫回目前時間。如果收到了"quit",對話將被關閉。該方法將目前時間發往用戶端,依賴於你使用的協議編碼,發送至方法的對象(第二個參數)會有不同,發送到session.write(Object)方法的對象類同。如果你沒有指定協議編碼,則一般會收到ByteBuffer對象,而發送的也要是ByteBuffer對象。

sessionCreated方法用於對話初始化,在這裡,先列印一條資訊,然後判斷對話的類型,再設定緩衝大小,這裡設定的是2048個位元組。空閑時間設定為10秒,如果覆蓋了sessionIdle方法,則該方法每10秒被呼叫一次。

3    測試

到這裡,編譯器。如果成功,那麼運行,然後telnet這個程式,如下所示:

用戶端內容:
user@myhost:~> telnet 127.0.0.1 9123
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
hello
Mon Apr 09 23:42:55 EDT 2007
quit
Connection closed by foreign host.
user@myhost:~>

服務端內容:
MINA Time server started.
Session created...
Message written...

4 參考文檔

    Apache MINA Quick Start Guide http://mina.apache.org/documentation.html

      Added by Mark Webb, last edited by Trustin Lee on Apr 16, 2007    (view change)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.