Xmpp获取离线消息
Posted tiancai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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获取离线消息的主要内容,如果未能解决你的问题,请参考以下文章