Xmpp獲取離線消息
文章只是選取了其中一段,無XMPP基礎的人可能看起來有點復雜;
假設我們註冊了一個用戶,用戶名叫shimiso,那麽我們如何讓shimiso這個用戶一登陸就取到離線消息呢?
PPConnection.DEBUG_ENABLED = false; AccountManager accountManager; final ConnectionConfiguration connectionConfig = new ConnectionConfiguration( "192.168.1.78", Integer.parseInt("5222"), "csdn.shimiso.com");// 允許自動連接 connectionConfig.setReconnectionAllowed(true); connectionConfig.setSendPresence(false);//不要告訴服務器自己的狀態 Connection connection = new XMPPConnection(connectionConfig); try { connection.connect();// 開啟連接 accountManager = connection.getAccountManager();// 獲取賬戶管理類 } catch(XMPPException e) { throw new IllegalStateException(e); } connection.login("shimiso", "123","SmackTest"); OfflineMessageManager offlineManager = new OfflineMessageManager( connection); try { Iterator<org.jivesoftware.smack.packet.Message> it = offlineManager .getMessages(); System.out.println(offlineManager.supportsFlexibleRetrieval()); System.out.println("離線消息數量: " + offlineManager.getMessageCount()); Map<String, ArrayList<Message>> offlineMsgs = new HashMap<String, ArrayList<Message>>(); while (it.hasNext()) { org.jivesoftware.smack.packet.Message message = it.next(); System.out .println("收到離線消息, Received from 【" + message.getFrom() + "】 message: " + message.getBody()); String fromUser = message.getFrom().split("/")[0]; if (offlineMsgs.containsKey(fromUser)) { offlineMsgs.get(fromUser).add(message); } else { ArrayList<Message> temp = new ArrayList<Message>(); temp.add(message); offlineMsgs.put(fromUser, temp); } } // 在這裏進行處理離線消息集合...... Set<String> keys = offlineMsgs.keySet(); Iterator<String> offIt = keys.iterator(); while (offIt.hasNext()) { String key = offIt.next(); ArrayList<Message> ms = offlineMsgs.get(key); for (int i = 0; i < ms.size(); i++) { System.out.println("-->" + ms.get(i)); } } offlineManager.deleteMessages(); } catch (Exception e) { e.printStackTrace(); } offlineManager.deleteMessages();//刪除所有離線消息 Presence presence = new Presence(Presence.Type.available); nnection.sendPacket(presence);//上線了 nnection.disconnect();//關閉連接
運行結果:
這裏我們需要特別當心的是先不要告訴openfire服務器你上線了,否則永遠也拿不到離線消息,用下面老外的話將就是在你上線之前去獲取離線消息,這麽設計是很有道理的。
The OfflineMessageManager helps manage offline messages even before the user has sent an available presence. When a user asks for his offline messages before sending an available presence then the server will not send a flood with all the offline messages when the user becomes online. The server will not send a flood with all the offline messages to the session that made the offline messages request or to any other session used by the user that becomes online.
同時拿到離線消息以後刪除離線消息offlineManager.deleteMessages();,同是通知服務器自己上線了。
https://blog.csdn.net/kazeik/article/details/44344609
Xmpp獲取離線消息