push研究——Apache Mina探索初步

  雖然google爲Android開發者提供了GCM實現push,但是因爲需要系統安裝了google play、google帳號、系統>2.2、google push服務器在國外等多種原因,在中國,Android上想實現push還需要自己努力。

        當前最火的開源push是基於xmpp協議的androidpn。androidpn是基於Mina框架的,所以這裏從Mina框架開始入手。

Server

下面通過簡單的例子來學習mina的使用。首先創建服務端,工程正使用了3個jar包

                       

看代碼:

  1. public class HelloMina {  
  2.     private static final int PORT = 9125;  
  3.       /**  
  4.        * @param args  
  5.        * @throws IOException   
  6.        */ 
  7.       public static void main(String[] args) throws IOException {  
  8.           //創建一個非阻塞的server端Socket ,用NIO  
  9.           IoAcceptor acceptor = new  NioSocketAcceptor();    
  10.           acceptor.getFilterChain().addLast( "logger"new LoggingFilter() );  
  11.           acceptor.getFilterChain().addLast( "codec"new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));  
  12.           // 設定服務器端的消息處理器  
  13.           acceptor.setHandler(  new MinaServerHandler() );        
  14.           acceptor.getSessionConfig().setReadBufferSize( 2048 );  
  15.           acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );  
  16.           // 服務器端綁定的端口  啓動服務  
  17.           acceptor.bind( new InetSocketAddress(PORT) );  
  18.                 
  19.         }  

HelloMina的處理器:

 

  1. /**  
  2.  * HelloMina的處理邏輯  
  3.  * @author zhangxy  
  4.  */ 
  5. class MinaServerHandler extends IoHandlerAdapter {  
  6.      @Override 
  7.         public void exceptionCaught( IoSession session, Throwable cause ) throws Exception{  
  8.             cause.printStackTrace();  
  9.             session.close();  
  10.         }  
  11.  
  12.         @Override 
  13.         public void messageReceived( IoSession session, Object message ) throws Exception  
  14.         {  
  15.             String str = message.toString();  
  16.             if( str.trim().equalsIgnoreCase("quit") ) {  
  17.                 session.close();  
  18.                 return;  
  19.             }  
  20.             System.err.println("收到客戶端發來的消息::"+str);    
  21.             StringBuilder buf = new StringBuilder(str.length());    
  22.             for (int i = str.length() - 1; i >= 0; i--) {    
  23.                 buf.append(str.charAt(i));    
  24.             }    
  25.         
  26.             // and write it back.    
  27.             session.write(buf.toString());   
  28.         }  
  29.  
  30.         @Override 
  31.         public void sessionIdle( IoSession session, IdleStatus status ) throws Exception{  
  32.             System.out.println( "IDLE " + session.getIdleCount( status ));  
  33.         }  
  34.  
  35.         @Override 
  36.         public void messageSent(IoSession session, Object message)  
  37.                 throws Exception {  
  38.             // TODO Auto-generated method stub  
  39.             super.messageSent(session, message);  
  40.               
  41.         }  
  42.  
  43.         @Override 
  44.         public void sessionClosed(IoSession session) throws Exception {  
  45.             // TODO Auto-generated method stub  
  46.             super.sessionClosed(session);  
  47.              System.out.println( "session closed");  
  48.         }  
  49.  
  50.         @Override 
  51.         public void sessionCreated(IoSession session) throws Exception {  
  52.             // TODO Auto-generated method stub  
  53.             super.sessionCreated(session);  
  54.              System.out.println( "session create");  
  55.         }  
  56.  
  57.         @Override 
  58.         public void sessionOpened(IoSession session) throws Exception {  
  59.             // TODO Auto-generated method stub  
  60.             super.sessionOpened(session);  
  61.              System.out.println( "session opened");  
  62.         }  
  63.           

client

下面是Client代碼,Client沒有使用NIO,使用的普通socket實現:

 

  1. public class HelloMinaClient {  
  2.     private Socket socket;    
  3.     private DataOutputStream out;    
  4.     private DataInputStream in;    
  5.     public HelloMinaClient() throws IOException {    
  6.     }    
  7.     
  8.     /**   
  9.      * @param args   
  10.      */    
  11.     public static void main(String[] args) throws Exception {    
  12.         // TODO Auto-generated method stub    
  13.         HelloMinaClient minaClient = new HelloMinaClient();    
  14.         minaClient.minaClient();    
  15.     }    
  16.     
  17.     /**   
  18.      *   發送消息   
  19.      * @param out   
  20.      */    
  21.     public void sendMessage(Socket s) {    
  22.         try {    
  23.              out = new DataOutputStream(s.getOutputStream());     
  24.             out.writeBytes("mina\n");    
  25.         } catch (IOException e) {    
  26.             // TODO Auto-generated catch block    
  27.             e.printStackTrace();    
  28.         }    
  29.     
  30.     }    
  31.         
  32.     public void receiveMessage(Socket s) {    
  33.         try {    
  34.              in = new DataInputStream(s.getInputStream());    
  35.              System.err.println("收到服務端發來的消息::"+in.readLine());    
  36.         } catch (Exception e) {    
  37.             e.printStackTrace();    
  38.         }    
  39.     }    
  40.     
  41.     public void minaClient() throws Exception {    
  42.         while (true) {    
  43.             try {    
  44.                 socket = new Socket("192.168.21.121"9124);    
  45.                 sendMessage(socket);    
  46.                 receiveMessage(socket);    
  47.                 out.close();    
  48.                 in.close();    
  49.                 Thread.sleep(5000);    
  50.             } catch (InterruptedException e) {    
  51.                 // TODO Auto-generated catch block    
  52.                 e.printStackTrace();    
  53.             } catch(Exception e){    
  54.                 e.printStackTrace();    
  55.             }finally {    
  56.                  try{    
  57.                    if(socket!=null)socket.close();  //斷開連接    
  58.                  }catch (IOException e) {e.printStackTrace();}    
  59.               }    
  60.         }    
  61.     }    
  62.  

SOCKET作爲短連接,即收發消息後SOCKET斷開一次,線程過5秒又建立連接收發消息。
 

 


/**
* @author 張興業
* 郵箱:xy-zhang#163.com
* android開發進階羣:278401545
http://blog.csdn.net/xyz_lmn

* http://xyzlmn.blog.51cto.com/
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章