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("002@127.0.0.1","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("002@10.39.73.150/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); }