Android平台基于asmack实现XMPP协议中的PubSub机制

本文主要介绍,在Android平台上基于asmack包,实现的PubSub机制,在PubSub中最重要的概念是节点Node,几乎所有的操作都要通过Node来实现:

1、创建节点

public void createnode(String NodeID)
 {
 ConfigureForm form = new ConfigureForm(FormType.submit);
          form.setNodeType(NodeType.leaf);
          form.setAccessModel(AccessModel.open);
          form.setPublishModel(PublishModel.open);
          form.setPersistentItems(true);
          form.setNotifyRetract(true) ;   
          form.setMaxItems(65535); 
     try 
      {
LeafNode my_leaf_node = manager.createNode(NodeID);
my_leaf_node.sendConfigurationForm(form); 
Log.i("MyError","创建成功");
  } 
     catch (XMPPException e) 
     {
     Log.i("MyError","创建失败");
e.printStackTrace();
 }  
     
 }

2、订阅节点

public void subscribe(String NodeID,final Context context)
 {
 try 
 {
LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeID);
my_leaf_node.addItemEventListener(new ItemEventListener() 
 {
public void handlePublishedItems(ItemPublishEvent items) 
{

PayloadItem temp = (PayloadItem)items.getItems().get(0);
  Log.i("MyError","接收消息");
  //Toast.makeText(PictureActivity.this, "连接成功"+pubSubAddress, Toast.LENGTH_SHORT).show();

}});

SubscribeForm subscriptionForm = new SubscribeForm(FormType.submit);
        subscriptionForm.setDeliverOn(true);
        subscriptionForm.setDigestFrequency(5000);
        subscriptionForm.setDigestOn(true);
        subscriptionForm.setIncludeBody(true);

List<Subscription> subscriptions = my_leaf_node.getSubscriptions();
           
           boolean flag = true;
           for (Subscription s : subscriptions)
           {
               if (s.getJid().equalsIgnoreCase(connection.getUser()))
               {
                   flag=false;
                break;
               }
           }
           
           
             if(flag)
             {
            my_leaf_node.subscribe(connection.getUser(), subscriptionForm);
             }

Log.i("MyError","订阅成功");
 }
 catch (XMPPException e) 
 {
 Log.i("MyError","订阅失败");
 e.printStackTrace();
 }
 }

3、发布消息

public void publish(String NodeId,String title,String content)
 {

SimplePayload payload = new SimplePayload("picture","pubsub:test:picture", "<picture xmlns='pubsub:test:picture'><title>"+title+"</title><content>"+content+"</content></picture>");
PayloadItem item=new PayloadItem("voice-guide"+System.currentTimeMillis(), payload);
try 
{
LeafNode node = (LeafNode) manager.getNode(NodeId);
System.out.println(item.toXML());
 
node.publish(item);
Log.i("MyError","发布成功");

catch (XMPPException e) 
{
Log.i("MyError","发布失败成功");
e.printStackTrace();
}
    
   
 }

4、设置权限,非常重要,很多开发者会忽视

public void setAFF(String NodeId,String Jid)//必须是Owner
 {

ArrayList<MyAffiliation> list = new ArrayList<MyAffiliation>();
  MyAffiliation affiliation  = new MyAffiliation(Jid,Affiliation.Type.owner);
  list.add(affiliation);
  try 
  {  
  LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeId);
 
  Packet reply = SyncPacketSend.getReply(connection, 
        createPubsubPacket(pubSubAddress,Jid,Type.SET,new MyAffiliationsExtension(list,NodeId),
    PubSubNamespace.valueOf("OWNER")));
  Log.i("MyError","设置成功");
  } 
  catch (XMPPException e) 
{   
  Log.i("MyError","设置失败");
e.printStackTrace();
}

}

源码:

package com.baidu.mapapi.demo.pubsub;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;import org.jivesoftware.smack.AndroidConnectionConfiguration;
import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smackx.pubsub.AccessModel;
import org.jivesoftware.smackx.pubsub.Affiliation;
import org.jivesoftware.smackx.pubsub.ConfigureForm;
import org.jivesoftware.smackx.pubsub.FormType;
import org.jivesoftware.smackx.pubsub.Item;
import org.jivesoftware.smackx.pubsub.ItemPublishEvent;
import org.jivesoftware.smackx.pubsub.LeafNode;
import org.jivesoftware.smackx.pubsub.NodeExtension;
import org.jivesoftware.smackx.pubsub.NodeType;
import org.jivesoftware.smackx.pubsub.PayloadItem;
import org.jivesoftware.smackx.pubsub.PubSubElementType;
import org.jivesoftware.smackx.pubsub.PubSubManager;
import org.jivesoftware.smackx.pubsub.PublishModel;
import org.jivesoftware.smackx.pubsub.SimplePayload;
import org.jivesoftware.smackx.pubsub.SubscribeForm;
import org.jivesoftware.smackx.pubsub.Subscription;
import org.jivesoftware.smackx.pubsub.listener.ItemEventListener;
import org.jivesoftware.smackx.pubsub.packet.PubSub;
import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace;
import org.jivesoftware.smackx.pubsub.packet.SyncPacketSend;import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class PubSubService
{public   String pubSubAddress;public   PubSubManager manager;public   AndroidConnectionConfiguration connConfig ;public   XMPPConnection connection = new XMPPConnection(connConfig);public   List<org.jivesoftware.smackx.pubsub.Subscription> SubscriptionItem;public   Button sub ;public   List<? extends Item> NodeItems;public    List<XMLInfo> sceneryinfo = new  ArrayList<XMLInfo>();public String str;public void login(String Ip,String username,String passwaord){//SmackAndroid.init(this); try {connConfig = new AndroidConnectionConfiguration(Ip, 5222);connection = new XMPPConnection(connConfig);connection.connect();  connection.login(username, passwaord);pubSubAddress = "pubsub."+ connection.getServiceName();manager = new PubSubManager(connection,pubSubAddress);Log.i("MyError","连接成功");    }catch (XMPPException e) {Log.i("MyError","连接失败");      e.printStackTrace();}}public void createnode(String NodeID){ConfigureForm form = new ConfigureForm(FormType.submit);form.setNodeType(NodeType.leaf);form.setAccessModel(AccessModel.open);form.setPublishModel(PublishModel.open);form.setPersistentItems(true);form.setNotifyRetract(true) ;   form.setMaxItems(65535); try {LeafNode my_leaf_node = manager.createNode(NodeID);my_leaf_node.sendConfigurationForm(form); Log.i("MyError","创建成功");   } catch (XMPPException e) {Log.i("MyError","创建失败");     e.printStackTrace();}  }public void subscribe(String NodeID,final Context context){try {LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeID);my_leaf_node.addItemEventListener(new ItemEventListener() {public void handlePublishedItems(ItemPublishEvent items) {                      PayloadItem temp = (PayloadItem)items.getItems().get(0);Log.i("MyError","接收消息");//Toast.makeText(PictureActivity.this, "连接成功"+pubSubAddress, Toast.LENGTH_SHORT).show();   }});SubscribeForm subscriptionForm = new SubscribeForm(FormType.submit);subscriptionForm.setDeliverOn(true);subscriptionForm.setDigestFrequency(5000);subscriptionForm.setDigestOn(true);subscriptionForm.setIncludeBody(true);List<Subscription> subscriptions = my_leaf_node.getSubscriptions();boolean flag = true;for (Subscription s : subscriptions){if (s.getJid().equalsIgnoreCase(connection.getUser())){    flag=false;break;}}if(flag){my_leaf_node.subscribe(connection.getUser(), subscriptionForm);}Log.i("MyError","订阅成功");   }catch (XMPPException e) {Log.i("MyError","订阅失败");  e.printStackTrace();}}public void publish(String NodeId,String title,String content){SimplePayload payload = new SimplePayload("picture","pubsub:test:picture", "<picture xmlns='pubsub:test:picture'><title>"+title+"</title><content>"+content+"</content></picture>");PayloadItem item=new PayloadItem("voice-guide"+System.currentTimeMillis(), payload);try {LeafNode node = (LeafNode) manager.getNode(NodeId);System.out.println(item.toXML());node.publish(item);Log.i("MyError","发布成功");    } catch (XMPPException e) {Log.i("MyError","发布失败成功");   e.printStackTrace();}}public boolean mGetItems(String nodeID){     try {LeafNode node = (LeafNode) manager.getNode(nodeID);//  node.deleteAllItems();SubscriptionItem=node.getSubscriptions(); String subscriptionId=null;for(int i=0;i<SubscriptionItem.size();i++){if(SubscriptionItem.get(i).getJid().equalsIgnoreCase(connection.getUser())){subscriptionId=SubscriptionItem.get(i).getId();  break;}}System.out.println( subscriptionId);NodeItems = node.getItems(8,"eBB5GyMzzQPAIgkMwnn4N3YkD6FN944Cu6Qsmz4h");System.out.println(NodeItems.size());Log.i("MyError","获取成功");                } catch (XMPPException e) {Log.i("MyError","获取失败");     e.printStackTrace();return false;}try {   ListIterator lit = NodeItems.listIterator();while(lit.hasNext()){PayloadItem a = (PayloadItem) lit.next();System.out.println( a.toXML().length()+"gbwx");if(a.toXML().length()>10000){File file = new File("/mnt/sdcard/MyPubSubXMl/getxml.xml");FileOutputStream fis = new FileOutputStream(file);fis.write(a.toXML().getBytes());fis.close();File file1 = new File("/mnt/sdcard/MyPubSubXMl/getxml.xml");FileInputStream inStream;inStream = new FileInputStream(file1);XMLInfo temp = PullPersonService.readXml(inStream).get(0);inStream.close();sceneryinfo.add(temp);}lit.next();}System.out.println( sceneryinfo.size()+"drdrdr");//File file2 = new File("/mnt/sdcard/BitGuide/xinjiao.jpg");//FileOutputStream fis2 = new FileOutputStream(file2);//MyPubSubImg .generateImage(sceneryinfo.get(0).getcontent(), fis2);           }catch (Exception e) {Log.e("MyError","异常");e.printStackTrace();}return true;}public void setAFF(String NodeId,String Jid)//必须是Owner{ArrayList<MyAffiliation> list = new ArrayList<MyAffiliation>();MyAffiliation affiliation  = new MyAffiliation(Jid,Affiliation.Type.owner);list.add(affiliation);try {  LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeId);   Packet reply = SyncPacketSend.getReply(connection, createPubsubPacket(pubSubAddress,Jid,Type.SET,new MyAffiliationsExtension(list,NodeId),PubSubNamespace.valueOf("OWNER")));Log.i("MyError","设置成功");    } catch (XMPPException e) {   Log.i("MyError","设置失败");  e.printStackTrace();} }static PubSub createPubsubPacket(String to, String from,Type type, PacketExtension ext, PubSubNamespace ns) { PubSub request = new PubSub(); request.setTo(to); request.setType(type); request.setFrom(from);if (ns != null) { request.setPubSubNamespace(ns); } request.addExtension(ext); return request; } }class MyAffiliation implements PacketExtension
{  protected String jid; protected Affiliation.Type affiliation;public MyAffiliation(String jid, Affiliation.Type affiliation) { this.jid=jid; this.affiliation = affiliation; } public String getElementName() { return "affiliation"; } public String getNamespace() { return null; } public String toXML() { StringBuilder builder = new StringBuilder("<"); builder.append(getElementName()); appendAttribute(builder, "jid", jid); appendAttribute(builder, "affiliation", affiliation.toString());  builder.append("/>"); return builder.toString(); } private void appendAttribute(StringBuilder builder, String att, String value) { builder.append(" "); builder.append(att); builder.append("='"); builder.append(value); builder.append("'"); }
} class MyAffiliationsExtension extends NodeExtension
{protected List<MyAffiliation> affiliations = null;protected String node;public MyAffiliationsExtension(){super(PubSubElementType.AFFILIATIONS);}public MyAffiliationsExtension(List<MyAffiliation> subList,String node0){super(PubSubElementType.AFFILIATIONS);affiliations = subList;node=node0;}@Overridepublic String toXML(){if ((affiliations == null) || (affiliations.size() == 0)){return super.toXML();}else{StringBuilder builder = new StringBuilder("<");builder.append(getElementName());builder.append(" "); builder.append("node"); builder.append("='"); builder.append(node); builder.append("'"); builder.append(">");for (MyAffiliation item : affiliations){builder.append(item.toXML());}builder.append("</");builder.append(getElementName());builder.append(">");return builder.toString();}}
}

Android平台基于asmack实现XMPP协议中的PubSub机制相关推荐

  1. android camera2 采集,视频采集:Android平台基于Camera 2的实现

    前言 这篇文章简单介绍下移动端Android系统下利用Camera2相关API进行视频采集的方法. Camera2是谷歌在Android 5.0新增的用来替代Camera1操作摄像头的一个全新的API ...

  2. Android平台基于RTMP或RTSP的一对一音视频互动技术方案探讨

    背景 随着智能门禁等物联网产品的普及,越来越多的开发者对音视频互动体验提出了更高的要求.目前市面上大多一对一互动都是基于WebRTC,优点不再赘述,我们这里先说说可能需要面临的问题:WebRTC的服务 ...

  3. android平台基于卷积神经网络的识别

    相关理论知识 卷积神经网络 卷积神经网络(Convolutional Neural Networks, CNN)是一类包含卷积计算且具有深度结构的前馈神经网络,是深度学习的代表算法之一[][] .由于 ...

  4. 基于Windows Socket 的网络通信中的心跳机制原理

    引言 在采用TCP 连接的C/S 结构的系统中,当通信的一方正常关闭或退出时,另一方能收到相应的连接 断开的通知,然后进行必要的处理:但如果任意一方发生所谓的"非优雅断开",如:意 ...

  5. tcp欢动窗口机制_TCP协议中的窗口机制------滑动窗口详解

    一.窗口机制的分类 在TCP协议当中窗口机制分为两种: 1.固定的窗口大小 2.滑动窗口 二.固定窗口存在的问题 如下图所示: 我们假设这个固定窗口的大小为1,也就是每次只能发送一个数据,只有接收方对 ...

  6. tcp 协议中发送窗口的大小应该是_面试必备--TCP协议中的窗口机制滑动窗口详解...

    窗口机制分类 在TCP协议当中窗口机制分为两种: 1.固定的窗口大小 2.滑动窗口 固定窗口存在的问题 我们假设这个固定窗口的大小为1,也就是每次只能发送一个数据,只有接收方对这个数据进行了确认后才能 ...

  7. 关于OLSR协议中的MPR机制的阅读与理解

    主要参考Request For Comments7181-OLSRv2,及RFC文档进行理解 MPR机制简介 简介: MPR (MultiPoint Relay多点中继)机制是OLSR(Optimiz ...

  8. Android之基于xmpp openfire smack开发之openfire介绍和部署[1]

    http://blog.csdn.net/forlong401/article/details/33730365 前言 Java领域的即时通信的解决方案可以考虑openfire+spark+smack ...

  9. 即时聊天IM之一 XMPP协议简述

    合肥程序员群:49313181.    合肥实名程序员群:128131462 (不愿透露姓名和信息者勿加入) Q  Q:408365330     E-Mail:egojit@qq.com  综述: ...

最新文章

  1. 摘之知乎网友...PHYTIN学习
  2. 复习笔记(二)——C++面向对象设计和使用
  3. HDU - 2586 How far away ?(LCA)
  4. 前端学习(2241):react打卡倒计时十五天之react出现背景
  5. MVC中使用代码创建数据库(code first +mysql+EF)
  6. Eigen教程(1)之简介
  7. FPGA作业1:利用74161设计20进制计数器
  8. ArcGIS Engine打开shp文件
  9. 今天你18岁,父母的碎碎念
  10. mysql audit log_关于MySQL AUDIT(审计)那点事
  11. 华为云用docker部署halo
  12. 立创梁山派GD32F450ZGT6--屏幕扩展板LVGL应用
  13. 统计指标 --- 集中趋势
  14. 浅谈windows 编程中SendMessage函数的妙用!!!
  15. VR套装的一种低成本实现方式
  16. gunicorn配置文件
  17. 战地2服务器地图修改,《战地2》地图修改秘籍
  18. java计算机毕业设计猫咪伤患会诊复查医疗平台源代码+数据库+系统+lw文档
  19. 迈向图形化:dialog工具
  20. python中模拟上公交车

热门文章

  1. 冰与火之歌居然是在 DOS 系统上写出来的
  2. Kerberos协议内容详解
  3. 用户与角色的区别与联系
  4. Extract Method(提炼函数)
  5. 服务器上的文件怎么共享给学生机,云服务器学生机
  6. php大学生创意礼品电商平台的设计与实现
  7. 新浪微博API使用初步介绍——解决回调地址的问题
  8. 5.Python基础之面向对象
  9. 写了一个iPhone越狱快捷下拉开关插件
  10. MMORPG游戏设计