在Openfire中自带有Broadcase插件,可以让我们群发消息给全部用户或者组。不过如果是我们通过Servlet来实现这一功能,那么是能够增加一定的灵活性的。具体做法直接看Demo代码:
public class SafeServlet extends HttpServlet { private JID serverAddress; private MessageRouter router; private UserManager userManager; @Override public void init() throws ServletException { super.init(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.doGet(request, response); // 获取服务器地址 serverAddress = new JID(XMPPServer.getInstance().getServerInfo().getXMPPDomain()); router = XMPPServer.getInstance().getMessageRouter(); userManager = UserManager.getInstance(); System.out.println("Require SafeServlet GET Method"); // 创建消息类 final Message message = new Message(); message.setFrom(serverAddress); message.setSubject("Test subject"); message.setBody("Test body"); message.setType(Message.Type.chat); // 获取所有用户 Collection<User> users = userManager.getUsers(); String xmppdomain = "@" + JiveGlobals.getProperty("xmpp.domain"); // 对所有用户进行遍历,发送消息 for (User u : users) { // 创建需要发送消息的备份,只将发送对象进行修改 final Message newMessage = message.createCopy(); newMessage.setTo(u.getUsername() + xmppdomain); try { TimerTask messageTask = new TimerTask() { @Override public void run() { router.route(newMessage); } }; TaskEngine.getInstance().schedule(messageTask, 5000); } catch (Exception e) { Log.error(e.getMessage(), e); } } } @Override public void destroy() { super.destroy(); serverAddress = null; router = null; userManager = null; } }
Servlet的配置可以参考此文:http://www.cnblogs.com/ilovewindy/p/3834003.html
Openfire:通过Servlet群发消息,布布扣,bubuko.com
时间: 2024-11-05 09:14:42