码迷,mamicode.com
首页 > 其他好文 > 详细

Openfire:通过Servlet群发消息

时间:2014-07-15 00:41:44      阅读:469      评论:0      收藏:0      [点我收藏+]

标签:des   blog   http   java   for   io   

在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

Openfire:通过Servlet群发消息

标签:des   blog   http   java   for   io   

原文地址:http://www.cnblogs.com/ilovewindy/p/3834092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!