admin管理员组

文章数量:817310

spark+smack+openfire实现请求响应简单流程

当时我想知道的问题很简单 就是服务端如何返回给客户端一个字符串或者数字或者布尔值 客户端如何接收

现在分享出来给和我一样的初学者 泪奔中

简单的查询好友测试,客户端成功发送请求,服务端接收并返回响应结果。

 


源码版本 openfire 3.8.1

                 spark 2.5.0

测试前需将openfire及spark源码配置并发布成功,搭建简单测试环境,用户可成功登录。

 


一.客户端代码

1.测试IQ类


[java]
package org.jivesoftware.expand.send.test; 
 
import java.util.Collections; 
import java.util.Iterator; 
import java.util.List; 
import java.util.concurrent.CopyOnWriteArrayList; 
 
import org.jivesoftware.smack.packet.IQ; 
import org.jivesoftware.smackx.packet.DiscoverItems.Item; 
 
public class TestrrIQ extends IQ { 
    public static final String ELEMENT = "query"; 
    public static final String NAMESPACE = "jabber:iq:testrr"; //指定命名空间 服务端接收请求后将根据此命名空间调用业务处理类处理并响应请求 可以用B/S求响应方式套用理解  

package org.jivesoftware.expand.send.test;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.packet.DiscoverItems.Item;

public class TestrrIQ extends IQ {
 public static final String ELEMENT = "query";
 public static final String NAMESPACE = "jabber:iq:testrr"; //指定命名空间 服务端接收请求后将根据此命名空间调用业务处理类处理并响应请求 可以用B/S求响应方式套用理解 [java] view plaincopyprint? 
private final List<Item> items; 
private String node; 
 
@SuppressWarnings("unchecked") 
public TestrrIQ() { 
    this.items = new CopyOnWriteArrayList(); 

 
public void addItem(Item item) { 
    synchronized (this.items) { 
        this.items.add(item); 
    } 

 
public Iterator<Item> getItems() { 
    synchronized (this.items) { 
        return Collections.unmodifiableList(this.items).iterator(); 
    } 

 
public String getNode() { 
    return this.node; 

 
public void setNode(String node) { 
    this.node = node; 

 
public String getChildElementXML() { 
    StringBuilder buf = new StringBuilder(); 
     
    buf.append("<query xmlns=\"jabber:iq:testrr\""); 
     
    if (getNode() != null) { 
        buf.append(" node=\""); 
        buf.append(getNode()); 
        buf.append("\""); 
    } 
     
    buf.append(">"); 
     
    synchronized (this.items) { 
        for (Item item : this.items) { 
            buf.append(item.toXML()); 
        } 
    } 
     
    buf.append("</query>"); 
     
    return buf.toString(); 

 
 private final List<Item> items;
 private String node;

 @SuppressWarnings("unchecked")
 public TestrrIQ() {
  this.items = new CopyOnWriteArrayList();
 }

 public void addItem(Item item) {
  synchronized (this.items) {
   this.items.add(item);
  }
 }

 public Iterator<Item> getItems() {
  synchronized (this.items) {
   return Collections.unmodifiableList(this.items).iterator();
  }
 }

 public String getNode() {
  return this.node;
 }

 public void setNode(String node) {
  this.node = node;
 }

 public String getChildElementXML() {
  StringBuilder buf = new StringBuilder();
  
  buf.append("<query xmlns=\"jabber:iq:testrr\"");
  
  if (getNode() != null) {
   buf.append(" node=\"");
   buf.append(getNode());
   buf.append("\"");
  }
  
  buf.append(">");
  
  synchronized (this.items) {
   for (Item item : this.items) {
    buf.append(item.toXML());
   }
  }
  
  buf.append("</query>");
  
  return buf.toString();
 }
}

 


2.测试IQProvider类(解析服务端返回的packet)

[java]
package org.jivesoftware.expand.send.test; 
 
import org.jivesoftware.smack.packet.IQ; 
import org.jivesoftware.smack.provider.IQProvider; 
import org.xmlpull.v1.XmlPullParser; 
 
public class TestrrIQProvider implements IQProvider { 
    public IQ parseIQ(XmlPullParser xp) throws Exception { 
        TestrrIQ result = new TestrrIQ(); 
 
        System.out.println("gloabl name " + xp.getName()); 
        System.out.println("gloabl text " + xp.getText()); 
 
        while (true) { 
            int n = xp.next(); 
            if (n == XmlPullParser.START_TAG) { 
                System.out.println("gloabl name " + xp.getName()); 
                System.out.println("gloabl text " + xp.getText()); 
                if ("friend".equals(xp.getName())) { 
                    System.out.println("friend " + xp.nextText());// 我们要的东西在这里; 张三 李四 王五可以根据业务模型自己开发不同的解析工具类返回相应的实体  
                } 
            } else if (n == XmlPullParser.END_TAG) { 
                if ("query".equals(xp.getName())) { 
                    break; 
                } 
            } 
        } 
        return result; 
    } 

package org.jivesoftware.expand.send.test;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider;
import org.xmlpull.v1.XmlPullParser;

public class TestrrIQProvider implements IQProvider {
 public IQ parseIQ(XmlPullParser xp) throws Exception {
  TestrrIQ result = new TestrrIQ();

  System.out.println("gloabl name " + xp.getName());
  System.out.println("gloabl text " + xp.getText());

  while (true) {
   int n = xp.next();
   if (n == XmlPullParser.START_TAG) {
    System.out.println("gloabl name " + xp.getName());
    System.out.println("gloabl text " + xp.getText());
    if ("friend".equals(xp.getName())) {
     System.out.println("friend " + xp.nextText());// 我们要的东西在这里; 张三 李四 王五可以根据业务模型自己开发不同的解析工具类返回相应的实体
    }
   } else if (n == XmlPullParser.END_TAG) {
    if ("query".equals(xp.getName())) {
     break;
    }
   }
  }
  return result;
 }
}

 


3.客户端向服务端发送查询好友请求测试类

[java]
package org.jivesoftware.expand.send.test; 
 
import org.jivesoftware.smack.PacketCollector; 
import org.jivesoftware.smack.SmackConfiguration; 
import org.jivesoftware.smack.XMPPConnection; 
import org.jivesoftware.smack.filter.PacketFilter; 
import org.jivesoftware.smack.packet.IQ; 
import org.jivesoftware.smack.packet.Packet; 
import org.jivesoftware.smack.provider.ProviderManager; 
import org.jivesoftware.spark.SparkManager; 
 
public class SendIQTestrr { 
 
    public static void run() throws Exception { 
        ProviderManager.getInstance().addIQProvider(TestrrIQ.ELEMENT, 
                TestrrIQ.NAMESPACE, new TestrrIQProvider()); 
 
        XMPPConnection con = SparkManager.getConnection(); 
 
        PacketCollector collector = con 
                .createPacketCollector(new PacketFilter() { 
                    public boolean accept(Packet p) { 
                        System.out.println("accept packet xml = " + p.toXML()); 
                        if (p instanceof TestrrIQ) { 
                            TestrrIQ m = (TestrrIQ) p; 
                            System.out.println(p.toXML()); 
                            System.out.println(m.toXML()); 
                            return true; 
                        } 
                        return false; 
                    } 
                }); 
 
        TestrrIQ disco = new TestrrIQ(); 
 
        disco.setType(IQ.Type.GET); 
        disco.setNode(null); 
 
        con.sendPacket(disco); 
 
        Packet packet = collector.nextResult(SmackConfiguration 
                .getPacketReplyTimeout()); 
 
        collector.cancel(); 
 
        if (packet == null) { 
 
        } else { 
            System.out.println("final packet xml = " + packet.toXML()); 
        } 
 
        con.disconnect(); 
    } 

package org.jivesoftware.expand.send.test;

import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.spark.SparkManager;

public class SendIQTestrr {

 public static void run() throws Exception {
  ProviderManager.getInstance().addIQProvider(TestrrIQ.ELEMENT,
    TestrrIQ.NAMESPACE, new TestrrIQProvider());

  XMPPConnection con = SparkManager.getConnection();

  PacketCollector collector = con
    .createPacketCollector(new PacketFilter() {
     public boolean accept(Packet p) {
      System.out.println("accept packet xml = " + p.toXML());
      if (p instanceof TestrrIQ) {
       TestrrIQ m = (TestrrIQ) p;
       System.out.println(p.toXML());
       System.out.println(m.toXML());
       return true;
      }
      return false;
     }
    });

  TestrrIQ disco = new TestrrIQ();

  disco.setType(IQ.Type.GET);
  disco.setNode(null);

  con.sendPacket(disco);

  Packet packet = collector.nextResult(SmackConfiguration
    .getPacketReplyTimeout());

  collector.cancel();

  if (packet == null) {

  } else {
   System.out.println("final packet xml = " + packet.toXML());
  }

  con.disconnect();
 }
}

 

4.触发测试方法(可自行编写触发测试类界面)
[java]
//此处仅提供按钮触发代码  
        JButton jButton = new JButton(); 
        jButton.setLabel("hava a test"); 
         
        jButton.addMouseListener(new MouseListener() { 
 
            @Override 
            public void mouseClicked(MouseEvent e) { 
                System.out.println("wahahaha!"); 
                // buildCrowdList(); // TODO  
                try { 
                    SendIQTestrr.run(); 
                } catch (Exception e1) { 
                    // TODO Auto-generated catch block  
                    e1.printStackTrace(); 
                } 
            } 
 
            @Override 
            public void mouseEntered(MouseEvent e) { // TODO  
            } 
 
            @Override 
            public void mouseExited(MouseEvent e) { // TODO  
            } 
 
            @Override 
            public void mousePressed(MouseEvent e) { // TODO  
            } 
 
            @Override 
            public void mouseReleased(MouseEvent e) { // TODO  
            } 
        }); 

//此处仅提供按钮触发代码
  JButton jButton = new JButton();
  jButton.setLabel("hava a test");
  
  jButton.addMouseListener(new MouseListener() {

   @Override
   public void mouseClicked(MouseEvent e) {
    System.out.println("wahahaha!");
    // buildCrowdList(); // TODO
    try {
     SendIQTestrr.run();
    } catch (Exception e1) {
     // TODO Auto-generated catch block
     e1.printStackTrace();
    }
   }

   @Override
   public void mouseEntered(MouseEvent e) { // TODO
   }

   @Override
   public void mouseExited(MouseEvent e) { // TODO
   }

   @Override
   public void mousePressed(MouseEvent e) { // TODO
   }

   @Override
   public void mouseReleased(MouseEvent e) { // TODO
   }
  });


二.服务端代码

1.服务端业务处理类

[java]
package org.jivesoftware.expand.handler.crowd; 
 
import gnu.inet.encoding.IDNAException; 
 
import java.util.ArrayList; 
import java.util.Iterator; 
 
import org.dom4j.Element; 
import org.jivesoftware.expand.util.Dom4jElement; 
import org.jivesoftware.openfire.IQHandlerInfo; 
import org.jivesoftware.openfire.PacketException; 
import org.jivesoftware.openfire.SharedGroupException; 
import org.jivesoftware.openfire.XMPPServer; 
import org.jivesoftware.openfire.auth.UnauthorizedException; 
import org.jivesoftware.openfire.disco.ServerFeaturesProvider; 
import org.jivesoftware.openfire.handler.IQHandler; 
import org.jivesoftware.openfire.user.UserAlreadyExistsException; 
import org.jivesoftware.openfire.user.UserManager; 
import org.jivesoftware.util.LocaleUtils; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.xmpp.packet.IQ; 
import org.xmpp.packet.JID; 
import org.xmpp.packet.PacketError; 
 
public class IQTestrrHandler extends IQHandler implements 
        ServerFeaturesProvider { 
 
    private static final Logger Log = LoggerFactory 
            .getLogger(IQTestrrHandler.class); 
 
    private IQHandlerInfo info; 
 
    public IQTestrrHandler() { 
        super("XMPP User Crowd List Handler"); 
        info = new IQHandlerInfo("query", "jabber:iq:testrr"); 
    } 
 
    @Override 
    public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException { 
        System.out.println("IQLoadUserCrowdListHandler - handleIQ - begin"); 
        try { 
            IQ returnPacket = null; 
 
            System.out.println("IQLoadUserCrowdListHandler - handleIQ - 1"); 
 
            System.out.println("IQLoadUserCrowdListHandler - handleIQ - packet to xml = " 
                            + packet.toXML()); 
 
            JID recipientJID = packet.getTo(); 
 
            if (recipientJID == null 
                    || recipientJID.getNode() == null 
                    || !UserManager.getInstance().isRegisteredUser( 
                            recipientJID.getNode())) { 
                returnPacket = manageRoster(packet); 
            } 
            return returnPacket; 
        } catch (SharedGroupException e) { 
            IQ result = IQ.createResultIQ(packet); 
            result.setChildElement(packet.getChildElement().createCopy()); 
            result.setError(PacketError.Condition.not_acceptable); 
             
            return result; 
        } catch (Exception e) { 
            if (e.getCause() instanceof IDNAException) { 
                Log.warn(LocaleUtils.getLocalizedString("admin.error"), e); 
                IQ result = IQ.createResultIQ(packet); 
                result.setChildElement(packet.getChildElement().createCopy()); 
                result.setError(PacketError.Condition.jid_malformed); 
                 
                return result; 
            } else { 
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e); 
                IQ result = IQ.createResultIQ(packet); 
                result.setChildElement(packet.getChildElement().createCopy()); 
                result.setError(PacketError.Condition.internal_server_error); 
                 
                return result; 
            } 
        } 
    } 
 
    private IQ manageRoster(IQ packet) throws UnauthorizedException, 
            UserAlreadyExistsException, SharedGroupException { 
 
        IQ returnPacket = null; 
        JID sender = packet.getFrom(); 
 
        System.out.println("IQLoadUserCrowdListHandler - manageRoster - begin"); 
 
        IQ.Type type = packet.getType(); 
 
        try { 
            System.out.println("IQLoadUserCrowdListHandler - manageRoster - 1"); 
 
            if (IQ.Type.get == type) { 

package org.jivesoftware.expand.handler.crowd;

import gnu.inet.encoding.IDNAException;

import java.util.ArrayList;
import java.util.Iterator;

import org.dom4j.Element;
import org.jivesoftware.expand.util.Dom4jElement;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.PacketException;
import org.jivesoftware.openfire.SharedGroupException;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.disco.ServerFeaturesProvider;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.util.LocaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.PacketError;

public class IQTestrrHandler extends IQHandler implements
  ServerFeaturesProvider {

 private static final Logger Log = LoggerFactory
   .getLogger(IQTestrrHandler.class);

 private IQHandlerInfo info;

 public IQTestrrHandler() {
  super("XMPP User Crowd List Handler");
  info = new IQHandlerInfo("query", "jabber:iq:testrr");
 }

 @Override
 public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
  System.out.println("IQLoadUserCrowdListHandler - handleIQ - begin");
  try {
   IQ returnPacket = null;

   System.out.println("IQLoadUserCrowdListHandler - handleIQ - 1");

   System.out.println("IQLoadUserCrowdListHandler - handleIQ - packet to xml = "
       + packet.toXML());

   JID recipientJID = packet.getTo();

   if (recipientJID == null
     || recipientJID.getNode() == null
     || !UserManager.getInstance().isRegisteredUser(
       recipientJID.getNode())) {
    returnPacket = manageRoster(packet);
   }
   return returnPacket;
  } catch (SharedGroupException e) {
   IQ result = IQ.createResultIQ(packet);
   result.setChildElement(packet.getChildElement().createCopy());
   result.setError(PacketError.Condition.not_acceptable);
   
   return result;
  } catch (Exception e) {
   if (e.getCause() instanceof IDNAException) {
    Log.warn(LocaleUtils.getLocalizedString("admin.error"), e);
    IQ result = IQ.createResultIQ(packet);
    result.setChildElement(packet.getChildElement().createCopy());
    result.setError(PacketError.Condition.jid_malformed);
    
    return result;
   } else {
    Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    IQ result = IQ.createResultIQ(packet);
    result.setChildElement(packet.getChildElement().createCopy());
    result.setError(PacketError.Condition.internal_server_error);
    
    return result;
   }
  }
 }

 private IQ manageRoster(IQ packet) throws UnauthorizedException,
   UserAlreadyExistsException, SharedGroupException {

  IQ returnPacket = null;
  JID sender = packet.getFrom();

  System.out.println("IQLoadUserCrowdListHandler - manageRoster - begin");

  IQ.Type type = packet.getType();

  try {
   System.out.println("IQLoadUserCrowdListHandler - manageRoster - 1");

   if (IQ.Type.get == type) {[java] view plaincopyprint?<SPAN style="WHITE-SPACE: pre">             </SPAN>//自定义结果packet并返回  
                String xml = "<query xmlns='jabber:iq:testrr'><friends><friend jid='zs' name='张三'></friend><friend jid='ls' name='李四'></friend><friend jid='ww' name='王五'></friend></friends></query>"; 
 
                Element xmlElement = Dom4jElement.buildDom4jElement(xml); 
 
                returnPacket = IQ.createResultIQ(packet); 
                 
                returnPacket.setChildElement(xmlElement); 
 
                returnPacket.setType(IQ.Type.result); 
                returnPacket.setTo(sender); 
                returnPacket.setID(packet.getID()); 
                 
                System.out.println("IQLoadUserCrowdListHandler - manageRoster - returnPacket xml = " + returnPacket.toXML()); 
 
                //deliverer.deliver(returnPacket);   
            } 
        } catch (Exception e) { 
            throw new UnauthorizedException(e); 
        } 
        return returnPacket; 
    } 
 
    @Override 
    public void initialize(XMPPServer server) { 
        super.initialize(server); 
    } 
 
    @Override 
    public IQHandlerInfo getInfo() { 
        return info; 
    } 
 
    public Iterator<String> getFeatures() { 
        ArrayList<String> features = new ArrayList<String>(); 
        features.add("jabber:iq:testrr"); 
        return features.iterator(); 
    } 

    //自定义结果packet并返回
    String xml = "<query xmlns='jabber:iq:testrr'><friends><friend jid='zs' name='张三'></friend><friend jid='ls' name='李四'></friend><friend jid='ww' name='王五'></friend></friends></query>";

    Element xmlElement = Dom4jElement.buildDom4jElement(xml);

    returnPacket = IQ.createResultIQ(packet);
    
    returnPacket.setChildElement(xmlElement);

    returnPacket.setType(IQ.Type.result);
    returnPacket.setTo(sender);
    returnPacket.setID(packet.getID());
    
    System.out.println("IQLoadUserCrowdListHandler - manageRoster - returnPacket xml = " + returnPacket.toXML());

    //deliverer.deliver(returnPacket);
   }
  } catch (Exception e) {
   throw new UnauthorizedException(e);
  }
  return returnPacket;
 }

 @Override
 public void initialize(XMPPServer server) {
  super.initialize(server);
 }

 @Override
 public IQHandlerInfo getInfo() {
  return info;
 }

 public Iterator<String> getFeatures() {
  ArrayList<String> features = new ArrayList<String>();
  features.add("jabber:iq:testrr");
  return features.iterator();
 }
}

 

2.在org.jivesoftware.openfire.XMPPServer loadModules()方法中增加代码

[java]
loadModule(IQTestrrHandler.class.getName()); //服务端注册加载自定义的业务处理类 

loadModule(IQTestrrHandler.class.getName()); //服务端注册加载自定义的业务处理类服务端如何接收请求、如何调用到相应的处理类来进行业务处理并响应结果这种流程是初学者都关心的问题 

 

转自:.html

本文标签: sparksmackopenfire实现请求响应简单流程