MirrorNetwork 基于jmdns和netty的android網絡通信開源庫
來自: http://www.cnblogs.com/europelee/p/5186973.html
目前android很多開源的網絡通信庫大多是基于http, 像Volley, android-async-http等等 ,在WAN上的網絡通信是個不錯的解決方案,而對于在局域網內的通信場景,上面基于http的網絡通信仍然有效,但是并非所有的服務端都采用http服務,MirrorNetwork正是在這個需求下產生,它基于jmdns來實現服務自動發現,零網絡配置,基于netty來實現android設備間的網絡通信。
(1) 消息模型MirrorMessage
MirrorNetwork定義了一種消息模型MirrorMessage,它包含三個重要成員:
MIRROR_APPTYPE appType:消息承載的應用類型,使得MirrorNetwork收到該消息后,可以判斷將該消息分發給哪個應用上層的消息監聽對象(該類實現IMirrorMsgListener)。
String peerAddress:server使用,MirrorNetwork支持多個client同時連接一個server, server發送消息給其中一個client,需要指定該client的地址
Object content:消息承載的應用層需要的真正內容,應用層可以根據業務自定義content類,僅需要該類實現Serializable。
(2) 消息通信實體
MirrorNetwork定義了一個接口類INetworkConnection,通過這個接口類,我們可以自定義各種不同的具體通信實體,MirrorNetwork基于netty定義了兩個通信實體類NettyClient和NettyServer,這兩個類實現了INetworkConnection接口。
public interface INetworkConnection {
/**
*
* @Title: start
* @Description: cli/svr endpoint connects into network(connect/bind)
* void
* @throws
*/
public void start();
/**
*
* @Title: send
* @Description: send msg to peer, notice:
* for supporting cli:svr=*:1
* if svr sends msg to cli, mirrormessage req must set peerAddress.
* if cli sends msg to svr, peerAddress not need set.
* @param req
* @return
* MIRROR_TRANSFSTATUS
* @throws
*/
public MIRROR_NETSTATUS send(MirrorMessage req);
/**
*
* @Title: stop
* @Description: just close network connection, you can start again for connecting again
* recommend using stop for simple.
* void
* @throws
*/
public void stop();
/**
*
* @Title: close
* @Description: close network connection and release all resources.
* void
* @throws
*/
public void close();
/**
*
* @Title: setMirrorMsgListener
* @Description: set msglistener for recving msg from peers,
* you are allowed registering listener once for each appType.
* @param appType
* @param li
* @return
* boolean
* @throws
*/
public boolean setMirrorMsgListener(MIRROR_APPTYPE appType, IMirrorMsgListener li);
/**
*
* @Title: isClosed
* @Description: check if network connection was closed.
* @return
* boolean
* @throws
*/
public boolean isClosed();
}
通信實體(nettyclient, nettyserver)通過setMirrorMsgListener方法為每種業務層(指定MIRROR_APPTYPE)設置監聽對象,用來實現異步通信,接收對端消息。
MirrorNetwork的實現代碼和使用指南,請訪問 https://github.com/europelee/MirrorNetwork
</div> </div>