XMPP和即时通讯内容学习(二)

来源:互联网 发布:无形资产 软件 编辑:程序博客网 时间:2024/04/29 13:48

继续接着上面描述的内容写,上一篇内容我们是放松了一个消息给他人,那么我们怎么监听他人返回给我们消息呢?

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

运行上述代码,然后在控制台直接输入 nihao,这时spark客户端就会收到你所发出的消息,并可以进行回复,控制台和spark的截图如下:



这样互动就建立起来了,我这道这边这一步的时候很兴奋(初学者吗,都这样,大家见谅)!


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("bjsujb1@127.0.0.1");    newmsg.setSubject("重要通知");    newmsg.setBody("今天下午2点60分有会!");    newmsg.setType(Message.Type.headline);// normal支持离线     connection.sendPacket(newmsg);    connection.disconnect(); 

上面内容不懂,注意这段代码中多了一个Message对象,学习android的朋友肯定都这,这时一个消息的载体,可以携带很多内容,在这也不例外,设置发送对象,发送主题以及发送内容等;直接运行代码;你在spark端就会收到一条通知,截图如下:



今天就到这,过两天我们继续!