zoukankan      html  css  js  c++  java
  • openfire消息通知推送

    package cn.zsmy.utils.openfire;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Scanner;
    import java.util.UUID;
    
    import org.jivesoftware.smack.AccountManager;
    import org.jivesoftware.smack.Chat;
    import org.jivesoftware.smack.ChatManager;
    import org.jivesoftware.smack.ChatManagerListener;
    import org.jivesoftware.smack.Connection;
    import org.jivesoftware.smack.ConnectionConfiguration;
    import org.jivesoftware.smack.MessageListener;
    import org.jivesoftware.smack.Roster;
    import org.jivesoftware.smack.RosterEntry;
    import org.jivesoftware.smack.XMPPConnection;
    import org.jivesoftware.smack.XMPPException;
    import org.jivesoftware.smack.packet.Message;
    import org.jivesoftware.smack.packet.Presence;
    
    import cn.zsmy.constant.Constant;
    import cn.zsmy.init.DictInit;
    import cn.zsmy.utils.ImgBase64Util;
    /**
     * 
     * @author shm@2016-05-10
     * @version 1.0
     */
    public class OpenfireServer {
        
        private static String SERVER_NAME = "192.168.1.254";
        private static final String IP = "192.168.1.254";  
        private static final Integer DK = 5222;  
        
        
        private static Roster roster;
    
        /**
         * 获取连接
         * 
         * @return connection
         */
        public static Connection getConnection() {
            // ConnectionConfiguration config = new
            // ConnectionConfiguration(Constants.IP, Constants.DK);
            // ConnectionConfiguration config = new
            // ConnectionConfiguration(Global.fsConfig.getOpenfireIP(),
            // Integer.parseInt(Global.fsConfig.getOpenfirePort()));
            ConnectionConfiguration config = new ConnectionConfiguration(DictInit.dictMap.get(Constant.Dict.OPENFIRE_IP), Integer
                    .parseInt(DictInit.dictMap.get(Constant.Dict.OPENFIRE_PORT)));
            Connection connection = new XMPPConnection(config);
            Constant.MY_LOG.debug(connection.getSASLAuthentication());
            Constant.MY_LOG.debug(connection.getServiceName());
            return connection;
        }
    
        public static Connection login(String username, String pass) throws XMPPException {
            Connection con = OpenfireServer.getConnection();
            try {
                con.connect();
                con.loginAnonymously();//匿名登陆
                //con.login(username, pass);
            } catch (XMPPException e) {
                Constant.MY_LOG.debug("========登录异常=========");
                e.printStackTrace();
                throw e;
            }
            return con;
    
        }
        /**
         * 发送通知消息
         * 
         * @param username
         * @param pass
         * @param messgage
         * @param groupName
         * @throws XMPPException
         */
        public static void SendBCMsg(String username, String pass, String messgage, String groupName) throws XMPPException {
            Connection con = login(username, pass);
            Message m = new Message();
            m.setBody(messgage);// 设置消息。
            m.setTo(groupName + "@" + SERVER_NAME);// [groupname]@[serviceName].[serverName]
            con.sendPacket(m);
        }
    
        /**
         * 发送即时消息
         * 
         * @param username
         * @param pass
         * @param messgage
         * @throws XMPPException
         */
        /*
         * public static void SendMsg(String username, String pass, String messgage,
         * String toUser) throws XMPPException { Connection con = login(username,
         * pass); Chat mychat =
         * con.getChatManager().createChat(toUser+"@"+Constants.SERVER_NAME, //
         * 接收端的JID,JID是要加域的 new MessageListener() {
         * 
         * @Override public void processMessage(Chat chat, Message message) { String
         * messageBody = message.getBody(); Constants.MY_LOG.debug("收到信息:" +
         * messageBody + " " + message.getFrom()); } });
         * mychat.sendMessage(messgage); // 发送信息
         * 
         * con.disconnect(); // 断开连接 }
         */
    
        /**
         * 发送即时消息
         * 
         * @param username
         * @param pass
         * @param messgage
         * @throws XMPPException
         */
        public static void SendMsg(String username, String pass, String content, String toUser, String type, 
                String caseId, String identity, String filePath, String realPath, String senderId, String sendeeId) throws XMPPException {
            Connection con = login(username, pass);
            Chat mychat = con.getChatManager().createChat(toUser + "@" + DictInit.dictMap.get(Constant.Dict.OPENFIRE_HOST), // 接收端的JID,JID是要加域的
                    new MessageListener() {
                        @Override
                        public void processMessage(Chat chat, Message message) {
                            String messageBody = message.getBody();
                            Constant.MY_LOG.debug("收到信息:" + messageBody + " " + message.getFrom());
                        }
                    });
    
            Message msg = new Message();
            ChatInfo chatInfo = new ChatInfo();
            chatInfo.setCaseId(caseId);
            chatInfo.setIdentity(identity);
            chatInfo.setzType(type);
            chatInfo.setSenderid(senderId);
            chatInfo.setSendeeid(sendeeId);
            chatInfo.setZid(UUID.randomUUID().toString().replace("-", ""));
            chatInfo.setTag(toUser);
            if ("3".equals(type)) {
                chatInfo.setMsglength("0");
                // String filePath = "c://test.jpg";//待处理的图片
                // msg.setProperty("imgData", ImgBase64Util.getImgStr(realPath));
                msg.setBody(filePath);
            } else {
                chatInfo.setMsglength(content.length() + "");
                msg.setBody(content);
                // mychat.sendMessage(content);
            }
            msg.addExtension(chatInfo); // 添加扩展内容
            mychat.sendMessage(msg);
            con.disconnect(); // 断开连接
        }
    
        /**
         * 获取好友列表
         * 
         * @param username
         * @param pass
         * @return
         * @throws XMPPException
         */
        public static List<RosterEntry> getRosterList(String username, String pass) throws XMPPException {
            Connection con = login(username, pass);
            Collection<RosterEntry> rosters = con.getRoster().getEntries();
            for (RosterEntry rosterEntry : rosters) {
                System.out.print("name: " + rosterEntry.getName() + ",jid: " + rosterEntry.getUser()); // 此处可获取用户JID
                Constant.MY_LOG.debug("");
            }
            return null;
        }
    
        /**
         * 获取用户列表(含组信息)
         * 
         * @param username
         * @param pass
         * @return
         * @throws XMPPException
         */
        public List<RosterEntry> getRoster(String username, String pass) throws XMPPException {
            Connection con = login(username, pass);
            roster = con.getRoster();
            List<RosterEntry> EntriesList = new ArrayList<RosterEntry>();
            Collection<RosterEntry> rosterEntry = roster.getEntries();
            Iterator<RosterEntry> i = rosterEntry.iterator();
            while (i.hasNext()) {
                EntriesList.add(i.next());
            }
            return EntriesList;
        }
    
        public static void reciveMsg(String username, String pass) throws XMPPException {
            Connection con = login(username, pass);
            ChatManager cm = con.getChatManager(); // 取得聊天管理器
            // Chat chat = cm.createChat("hello@pc201511161109 ", null);
            // //得到与另一个帐号的连接,这里是一对一,@后面是你安装openfire时注册的域
    
            /*
             * 添加监听器
             */
            cm.addChatListener(new ChatManagerListener() {
    
                @Override
                public void chatCreated(Chat chat, boolean create) {
                    chat.addMessageListener(new MessageListener() {
    
                        @Override
                        public void processMessage(Chat chat, Message msg) {
                            if (msg.getBody() != null) {
                                Constant.MY_LOG.debug(chat.getParticipant() + ":" + msg.getBody());
                                try {
                                    chat.sendMessage("你刚才说的是:" + msg.getBody()); // 发送消息
                                } catch (XMPPException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                }
            });
    
            // chat.sendMessage("你猜"); //发送消息
    
            while (true); // 死循环,维持该连接不中断
    
            // connection.disconnect(); //断开连接
    
        }
    
        /**
         * 可以在控制台輸入內容,且可以接收对方发送的消息
         * 
         * @param username
         * @param pass
         * @param toUser
         * @throws XMPPException 
         */
        public static void test(String username, String pass, String toUser) throws XMPPException {
            Connection con = login(username, pass);
    
            // 登录
            ChatManager chatmanager = con.getChatManager();
            Chat newChat = chatmanager.createChat(toUser + "@" + SERVER_NAME, new MessageListener() {
                public void processMessage(Chat chat, Message message) {
                    if (message.getBody() != null) {
                        Constant.MY_LOG.debug("Received from 【" + message.getFrom() + "】 message: " + message.getBody());
                    }
    
                }
            });
            @SuppressWarnings("resource")
            Scanner input = new Scanner(System.in);
            while (true) {
                String message = input.nextLine();
                try {
                    newChat.sendMessage(message);
                } catch (XMPPException e) {
                    Constant.MY_LOG.debug("======发送异常=======");
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 测试openfire登录与消息发送是否可用
         * @param username
         * @param pass
         * @param toUser
         * @throws XMPPException
         */
        public static void testOpenfire(String username, String pass, String toUser) throws XMPPException {
            Connection con = login(username, pass);
            /*ChatManager chatmanager = con.getChatManager();
            Chat newChat = chatmanager.createChat(toUser + "@" + DictInit.dictMap.get(Constant.Dict.OPENFIRE_HOST), new MessageListener() {
                public void processMessage(Chat chat, Message message) {
                    if (message.getBody() != null) {
                        Constant.MY_LOG.debug("Received from 【" + message.getFrom() + "】 message: " + message.getBody());
                    }
                }
            });
            newChat.sendMessage("test server");*/
            con.disconnect(); //断开连接
        }
        
        /**
         * 新用户注册代码:
         * 
         * @param username
         * @param pass
         * @param toUser
         */
        public static void register(String username, String pass) {
            try {
                ConnectionConfiguration config = new ConnectionConfiguration(IP, DK);
                Connection connection = new XMPPConnection(config);
                connection.connect();
                AccountManager amgr = connection.getAccountManager();
                amgr.createAccount(username + "@" + SERVER_NAME, pass);
            } catch (XMPPException e) {
                Constant.MY_LOG.debug("======新用户注册异常============");
                e.printStackTrace();
            }
        }
    
        /**
         * 更改用户状态代码 上面的代码会把用户的状态改成Go fishing,但是还是显示在线的状态
         * 
         * @param username
         * @param pass
         * @param toUser
         */
        public static void updateStatus(String username, String pass) {
            Presence presence = new Presence(Presence.Type.available); // 这里如果改成unavailable则会显示用户不在线
            ConnectionConfiguration config = new ConnectionConfiguration(IP, DK);
            Connection connection = new XMPPConnection(config);
            try {
                connection.connect();
            } catch (XMPPException e) {
                Constant.MY_LOG.debug("=======更改用户状态异常========");
                e.printStackTrace();
            }
            presence.setStatus("Go fishing");
            connection.sendPacket(presence);
            connection.getRoster();
        }
    
        public static void SendMsg(String username, String pass, String messgage, String toUser) throws XMPPException {
            Connection con = login(username, pass);
            Chat mychat = con.getChatManager().createChat(toUser + "@" + SERVER_NAME, // 接收端的JID,JID是要加域的
            new MessageListener() {
                @Override
                public void processMessage(Chat chat, Message message) {
                    String messageBody = message.getBody();
                    Constant.MY_LOG.debug("收到信息:" + messageBody + " " + message.getFrom());
                }
            });
    
            Message msg = new Message();
            String imgFile = "c://test.jpg";// 待处理的图片
            String imgbese = ImgBase64Util.getImgStr(imgFile);
            Constant.MY_LOG.debug(imgbese.length());
            Constant.MY_LOG.debug(imgbese);
            msg.setProperty("imgData", imgbese);
            msg.setBody("upload/casePic/2016/5/11/14629304841938816.jpg");
            mychat.sendMessage(msg);
            // mychat.sendMessage(messgage); // 发送信息
    
            // con.disconnect(); // 断开连接
        }
    
        /**
         * 判断openfire用户的状态 strUrl : url格式 -
         * http://my.openfire.com:9090/plugins/presence
         * /status?jid=user1@my.openfire.com&type=xml 返回值 : 0 - 用户不存在; 1 - 用户在线; 2 -
         * 用户离线 说明 :必须要求 openfire加载 presence 插件,同时设置任何人都可以访问
         */
        public static short IsUserOnLine(String strUrl) {
            strUrl = "http://192.168.1.254:9090/plugins/presence/status?jid=15102123715@192.168.1.254";
            short shOnLineState = 0; // -不存在-
            try {
                URL oUrl = new URL(strUrl);
                URLConnection oConn = oUrl.openConnection();
                if (oConn != null) {
                    BufferedReader oIn = new BufferedReader(new InputStreamReader(oConn.getInputStream()));
                    if (null != oIn) {
                        String strFlag = oIn.readLine();
                        oIn.close();
    
                        if (strFlag.indexOf("type="unavailable"") >= 0) {
                            shOnLineState = 2;
                        }
                        if (strFlag.indexOf("type="error"") >= 0) {
                            shOnLineState = 0;
                        } else if (strFlag.indexOf("priority") >= 0 || strFlag.indexOf("id="") >= 0) {
                            shOnLineState = 1;
                        }
                    }
                }
            } catch (Exception e) {
    
            }
            return shOnLineState;
        }
    
        /**
         * 发送给指定用户的广播消息
         * 
         * @param fromUsername
         * @param fromUserPass
         * @param toUserName
         * @param subject
         * @param body
         * @throws XMPPException 
         */
        public static void broadcastMsgToUser(String fromUsername, String fromUserPass, String toUserName, String subject, String body) throws XMPPException {
            Connection con = login(fromUsername, fromUserPass);
            Message message = new Message();
            message.setFrom(fromUsername);
            message.setTo(toUserName+ "@" + DictInit.dictMap.get(Constant.Dict.OPENFIRE_HOST));
            message.setBody(body);
            message.setSubject(subject);
            message.setType(Message.Type.headline);  //Message.Type.headline为通知, 不传默认为广播
            con.sendPacket(message);
        }
    
        /**
         * 发送给全体用户的广播
         * 
         * @param username
         * @param pass
         * @param subject
         * @param content
         * @throws XMPPException
         */
        public static void broadcastMsgToAll(String username, String pass, String subject, String content) throws XMPPException {
            Connection con = login(username, pass);
            Message m = new Message();
            m.setBody(content);// 设置消息。
            m.setTo("all@broadcast." + SERVER_NAME);// all@broadcast.yyp-pc
                                                                // 说明一下只需要改后面的yyp-pc改成
                                                                // 相应的域名。
                                                                // 我这里是自己机器的名字。
            con.sendPacket(m);
        }
    
        public static void main(String[] args) throws XMPPException {
            SendMsg("13818440540", "13818440540", "900009", "15102123715", "1", "11111111", "doctor", null, null,"","");
            //broadcastMsgToUser("admin","admin", "13817764475", "123重要通知", "pppppppppp"+new Date());
            //broadcastMsgToAll("15102123715", "15102123715", "重要通知", " 全员广播消息测试!");
            // SendMsg("13818440540","13818440540","dcdvvkdvmdklmdd","15102123715");
            // getRosterList("hello1","123456");
            // reciveMsg("hello1","123456");
    
            // test("13818440540","123456","15102123715");
            // register("qwertyuiop", "123456");
            // updateStatus("hello1","123456");
            Constant.MY_LOG.debug(IsUserOnLine(""));;
        }
    
    }
  • 相关阅读:
    面试常见问题汇总
    java static变量及函数
    java自定义注解及其信息提取
    testNG 注释实例
    让我欲罢不能的node.js
    利用html 5 websocket做个山寨版web聊天室(手写C#服务器)
    html5 Web Workers
    html5 postMessage解决跨域、跨窗口消息传递
    C# socket编程实践——支持广播的简单socket服务器
    简单理解Socket
  • 原文地址:https://www.cnblogs.com/shihaiming/p/6210799.html
Copyright © 2011-2022 走看看