Smack+OpenFire搭建IM通訊,包含心跳和自動重連(Android實現),smackopenfire
Smack是一個開源,便於使用的XMPP(jabber)用戶端類庫。優點:簡單的,功能強大,給使用者發送資訊只需三行代碼便可完成。缺點:API並非為大量並發使用者設計,每個客戶要1個線程,佔用資源大。
OpenFire是開源的、基於可拓展通訊和表示協議(XMPP)、採用Java程式設計語言開發的即時協作伺服器。 Openfire安裝和使用都非常簡單,並利用Web進行管理。單台伺服器可支援上萬並發使用者。
1、首先到網址 http://www.igniterealtime.org 下載OpenFire伺服器和Smack jar包
2、安裝OpenFire登陸到控制台
這裡設定多長時間關閉閑置串連,可以判斷使用者是否線上的最長反應時間
3、建立兩個測試帳號,先用Spark登陸一個帳號
4、手機端登陸,使用Service保持串連,並與spark端發送訊息,實現雙向通訊(代碼和程式在後面)
5、關鍵代碼
配置串連OpenFire伺服器,串連成功後設定響應Linstener和Receiver,這裡因業務需求設定ping間隔為10s
1 public void connect() { 2 Log.i(TAG, "connect()"); 3 XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); 4 configBuilder.setHost(SmackConst.XMPP_HOST); 5 configBuilder.setServiceName(SmackConst.SERVICE_NAME); 6 configBuilder.setUsernameAndPassword(mUsername, mPassword); 7 configBuilder.setSecurityMode(SecurityMode.disabled); 8 mConnection = new XMPPTCPConnection(configBuilder.build()); 9 //Set ConnectionListener here to catch initial connect();10 mConnection.addConnectionListener(this);11 try {12 mConnection.connect();13 mConnection.login();14 if(mConnection.isAuthenticated()){//登入成功15 MyPingManager.setDefaultPingInterval(10);//Ping every 10 seconds16 MyPingManager myPingManager = MyPingManager.getInstanceFor(mConnection);17 //Set PingListener here to catch connect status18 myPingManager.registerPingFailedListener(SmackConnection.this);19 setupSendMessageReceiver();20 //Set ChatListener here to catch receive message and send NEW_MESSAGE broadcast21 ChatManager.getInstanceFor(mConnection).addChatListener(this);22 //Set ChatListener here to catch roster change and rebuildRoster23 //Roster.getInstanceFor(mConnection).addRosterListener(this);24 sendLoginBroadcast(true);25 }else{26 mConnection.disconnect();27 Log.i(TAG, "Authentication failure");28 sendLoginBroadcast(false);29 }30 } catch (Exception e) {31 e.printStackTrace();32 sendLoginBroadcast(false);33 Intent intent = new Intent(mService, mService.getClass());34 mService.stopService(intent);35 }36 37 }
自動重連TimerTask,Ping失敗後啟動,重連成功後關閉
1 private Timer reConnectTimer; 2 private int delay = 10000; 3 //pingFailed時啟動重連線程 4 class ReConnectTimer extends TimerTask { 5 @Override 6 public void run() { 7 // 無網路連接時,直接返回 8 if (getNetworkState(mService) == NETWORN_NONE) { 9 Log.i(TAG, "無網路連接,"+delay/1000+"s後重新串連");10 reConnectTimer.schedule(new ReConnectTimer(), delay);11 //reConnectTimer.cancel();12 return;13 }14 // 串連伺服器 15 try {16 mConnection.connect();17 if(!mConnection.isAuthenticated()){18 mConnection.login();19 reConnectTimer.cancel();20 }21 Log.i(TAG, "重連成功");22 Intent intent = new Intent(SmackConst.ACTION_RECONNECT_SUCCESS);23 mService.sendBroadcast(intent);24 } catch (Exception e) {25 Log.i(TAG, "重連失敗,"+delay/1000+"s後重新串連");26 e.printStackTrace();27 reConnectTimer.schedule(new ReConnectTimer(), delay);28 } 29 30 } 31 }
資源地址:https://github.com/liuhaijin/Smack-Openfire
菜鳥一枚,共同學習~~