Smack 自定义 IQ


reference :http://how.vndemy.com/networking/1083-sending-and-receiving-custom-xmpp-iq-with-smack/

 using custom XMPP IQ message. And we must implement an IQProvider to parse correctly our custom iq message.

I suppose our custom message looks like this:

<iq type="set" id="440-125" to="lili2@lonny-pc/Smack">
    <notification xmlns="hples:iq:notification">
        <id>c8451ed9</id>
        <title>presence</title>
        <message>online</message>
    </notification>
</iq>

Then we will create two java classes name NotificationIQ and NotificationIQProvider:

NotificationIQ  继承IQ 类 

public class NotificationIQ extends IQ {

    private String id;

    private String title;

    private String message;

    public NotificationIQ() {
    }

    @Override
    public String getChildElementXML() {
        StringBuilder buf = new StringBuilder();
        buf.append("<").append("notification").append(" xmlns=\"").append(
                "hples:iq:notification").append("\">");
        if (id != null) {
            buf.append("<id>").append(id).append("</id>");
        }
        buf.append("</").append("notification").append("> ");
        return buf.toString();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

NotificationIQProvider   samck will  invoke right provider to parse  received IQ very import

/**
 * This class parses incoming IQ packets to NotificationIQ objects.
 */
public class NotificationIQProvider implements IQProvider {

	public NotificationIQProvider() {
	}

	@Override
	public IQ parseIQ(XmlPullParser parser) throws Exception {

		NotificationIQ notification = new NotificationIQ();
		boolean done = false;
		while (!done) {
			int eventType = parser.next();
			if (eventType == 2) {
				if ("id".equals(parser.getName())) {
					notification.setId(parser.nextText());
				}
				if ("title".equals(parser.getName())) {
					notification.setTitle(parser.nextText());
				}
				if ("message".equals(parser.getName())) {
					notification.setMessage(parser.nextText());
				}

			} else if (eventType == 3 && "notification".equals(parser.getName())) {
				done = true;
			}
		}

		return notification;
	}
}

   create listener 

public class NotificationPacketListener implements PacketListener {

	@Override
	public void processPacket(Packet packet) {
		System.out.println(packet.getFrom()+" : "+packet.getTo());
		  if (packet instanceof NotificationIQ) {
	            NotificationIQ notification = (NotificationIQ) packet;

	            if (notification.getChildElementXML().contains("hples:iq:notification")) {
	                String notificationId = notification.getId();
	                String notificationTitle = notification.getTitle();
	                String notificationMessage = notification.getMessage();
	      
	            }   
		  }     
	}

	
	
}

registe provider

static {
		ProviderManager.getInstance().addIQProvider("notification", "hples:iq:notification",
				new NotificationIQProvider());
	}

test code

connect.addPacketListener(new NotificationPacketListener(), new IQTypeFilter(IQ.Type.SET));



how to create customer  IQ on server

    /**
     * Sends a newly created notification message to the specific user.
     * 
     * @param apiKey the API key
     * @param title the title
     * @param message the message details
     * @param uri the uri
     */
    public void sendNotifcationToUser(JID username,
            String title, String message) {
        log.debug("sendNotifcationToUser()...");
        IQ notificationIQ = createNotificationIQ(title, message);
        ClientSession session = sessionManager.getSession(username);
        if (session != null) {
            if (session.getPresence().isAvailable()) {
                notificationIQ.setTo(session.getAddress());
               // session.deliverRawText(notificationIQ.toString());
                try {
				//	XMPPServer.getInstance().getPacketDeliverer().deliver(notificationIQ);
                	XMPPServer.getInstance().getRoutingTable().routePacket(username, notificationIQ, true);
					
				} catch (PacketException e) {
					e.printStackTrace();
				} 
                
                
            }
        }
    }

    /**
     * Creates a new notification IQ and returns it.
     */
    private IQ createNotificationIQ(String title,String message) {
        Random random = new Random();
        String id = Integer.toHexString(random.nextInt());
        Element notification = DocumentHelper.createElement(QName.get(
                "notification", NOTIFICATION_NAMESPACE));
        notification.addElement("id").setText(id);
        notification.addElement("title").setText(title);
        notification.addElement("message").setText(message);

        IQ iq = new IQ();
        iq.setType(IQ.Type.set);
        iq.setChildElement(notification);

        return iq;
    }

 

send packet:

XMPPServer.getInstance().getRoutingTable().routePacket(username, notificationIQ, true);


转载于:https://my.oschina.net/u/2308353/blog/603322

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值