1. 程式人生 > >openfire 傳送 接受 註冊 廣播 好友列表 線上狀態

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 [email protected] * @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("[email protected] ", 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 * /[email protected]&type=xml 返回值 : 0 - 使用者不存在; 1 - 使用者線上; 2 - * 使用者離線 說明 :必須要求 openfire載入 presence 外掛,同時設定任何人都可以訪問 */ public static short IsUserOnLine(String strUrl) { strUrl = "http://192.168.1.254:9090/plugins/presence/[email protected]"; 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("[email protected]" + SERVER_NAME);// [email protected] // 說明一下只需要改後面的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(""));; } }