1. 程式人生 > >openfire維持線上狀態,監聽訊息

openfire維持線上狀態,監聽訊息

  public  static  void  testLoginStatus()throws  XMPPException,InterruptedException {
        AccountManager accountManager;
        final ConnectionConfiguration connectionConfig = new ConnectionConfiguration("127.0.0.1", Integer.parseInt("5222"), "");
// 允許自動連線
        connectionConfig.setReconnectionAllowed(true
); connectionConfig.setSendPresence(false); final Connection connection = new XMPPConnection(connectionConfig); try { connection.connect();// 開啟連線 accountManager = connection.getAccountManager();// 獲取賬戶管理類 } catch (XMPPException e) {
throw new IllegalStateException(e); } connection.login("001", "001", ""); Presence presence=new Presence(Presence.Type.available); presence.setStatus("1"); connection.sendPacket(presence); ProviderManager.getInstance().addIQProvider("ping", "urn:xmpp:ping
", new PingIQProvider()); connection.addPacketListener(new PacketListener() { @Override public void processPacket(Packet p) { try { Thread.sleep(50000); } catch (Exception ex){} PingIQ pingIQ = (PingIQ) p; IQ pongIQ = pingIQ.createResultIQ(pingIQ); // 返回 connection.sendPacket(pongIQ); }}, new PacketTypeFilter(PingIQ.class)); //Roster roster=connection.getRoster(); //roster.createEntry("[email protected]","001", new String[]{"Friends"}); //監聽接收到的訊息 包括單聊 群聊 和廣播 // ChatManager cm=connection.getChatManager(); // 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) { // try { // System.out.println("cm:"+msg.getBody()); // System.out.println(chat.getParticipant()); // chat.sendMessage("你剛才說的是:" + msg.getBody()); // 傳送訊息 // } catch (XMPPException e) { // e.printStackTrace(); // } // } // } // }); // } // }); //單聊監聽 Chat mychat = connection.getChatManager().createChat("[email protected]/Spark", // 接收端的JID,JID是要加域的 new MessageListener() { @Override public void processMessage(Chat chat, Message message) { String messageBody = message.getBody(); try { if (message.getBody()!=null) { System.out.println("接受到來自002的訊息:" + message.getBody()); chat.sendMessage("您發的訊息是:" + message.getBody()); } }catch (Exception ex){ System.out.println(ex.getMessage()); } } }); Message msg = new Message(); msg.setBody("upload/casePic/2016/5/11/14629304841938816.jpg"); mychat.sendMessage(msg); // connection.disconnect(); while (true); }