继续接着上面描述的内容写,上一篇内容我们是放松了一个消息给他人,那么我们怎么监听他人返回给我们消息呢?
1、创建消息监听,监听消息队列的内容:
XMPPConnection.DEBUG_ENABLED = false; AccountManager accountManager; final ConnectionConfiguration connectionConfig = new ConnectionConfiguration( "127.0.0.1", Integer.parseInt("5222"), "127.0.0.1"); // 允许自动连接 connectionConfig.setReconnectionAllowed(true); connectionConfig.setSendPresence(true); Connection connection = new XMPPConnection(connectionConfig); try { connection.connect();// 开启连接 accountManager = connection.getAccountManager();// 获取账户管理类 } catch (XMPPException e) { throw new IllegalStateException(e); } connection.login("sujingbo", "123456"); System.out.println(connection.getUser());上面是继续昨天的代码,与openfire建立连接,接下来就是监听消息队列了:
//创建用户监听,监听消息队列,实现互动聊天。 ChatManager chatmanager = connection.getChatManager(); Chat newChat = chatmanager.createChat("[email protected]", new MessageListener() { public void processMessage(Chat chat, Message message) { if (message.getBody() != null) { System.out.println("Received from 【" + message.getFrom() + "】 message: " + message.getBody()); } } }); Scanner input = new Scanner(System.in); while (true) { String message = input.nextLine(); newChat.sendMessage(message); }
这样互动就建立起来了,我这道这边这一步的时候很兴奋(初学者吗,都这样,大家见谅)!
2、发送系统通知
大家都知道,作为一款即时通许软件都会有一个系统发送通知,通知所有联系人,废话不多话,代码如下:
XMPPConnection.DEBUG_ENABLED = false; // AccountManager accountManager; final ConnectionConfiguration connectionConfig = new ConnectionConfiguration( "127.0.0.1", Integer.parseInt("5222"), "127.0.0.1"); // 允许自动连接 connectionConfig.setReconnectionAllowed(true); connectionConfig.setSendPresence(true); Connection connection = new XMPPConnection(connectionConfig); try { connection.connect();// 开启连接 // accountManager = connection.getAccountManager();// 获取账户管理类 } catch (XMPPException e) { throw new IllegalStateException(e); } connection.login("sujingbo", "123456"); System.out.println(connection.getUser()); //创建通知内容并发送 Message newmsg = new Message(); newmsg.setTo("[email protected]"); newmsg.setSubject("重要通知"); newmsg.setBody("今天下午2点60分有会!"); newmsg.setType(Message.Type.headline);// normal支持离线 connection.sendPacket(newmsg); connection.disconnect();
今天就到这,过两天我们继续!