项目中有这么一个需求:
1. 间隔一分钟,查询XMPP服务器,获取在某个聊天室中的成员信息
2. 获取查询结果,做相应处理
查询XMPP协议,发现XEP-0045文档有做相关的协议说明:http://xmpp.org/extensions/xep-0045.html#disco-roomitems ,用到的是多用户聊天室(MUC)的discovery操作,对应的Namespace Uri为:
http://jabber.org/protocol/disco#items
查询消息定义:
<iq from='you jid'
id='message id'
to='roomJid'
type='get'>
<query xmlns='http://jabber.org/protocol/disco#items'/>
</iq>
正常的查询结果消息格式定义:
<iq from='roomJid'
id='message id'
to='you jid'
type='result'>
<query xmlns='http://jabber.org/protocol/disco#items'>
<item jid='roomJid/member1NickName'/>
<item jid='roomJid/member2NickName'/>
</query>
</iq>
如果该房间是私有房间,按照XEP-0030文档协议,可能返回的消息是一个空查询:
<iq from='roomJid'
id='message id'
to='you jid'
type='result'>
<query xmlns='http://jabber.org/protocol/disco#items' />
</iq>
通用的做法是拼接XML,然后发送,然后处理Iq到达消息。不同的库封装方法可能不一样,但是底层发送出去时,必然都是一样的XML文本。
我用的XMPP库是agsXMPP,具体的实现代码如下:
查询:
Jid roomJid = new Jid("roomName","domain.com");
/// <summary>
/// 查询聊天室内成员
/// </summary>
private void QueryMembers()
{
DiscoItemsIq discoItemIq = new DiscoItemsIq(IqType.get)
discoItemIq.To = roomJid;
xmppConnection.IqGrabber.SendIq(discoItemIq , new IqCB(QueryIqHandler), null);
//更简单的操作:DiscoManager discoM = new DiscoManager(xmppConnection);
//discoM.DiscoverItems(roomJid, new IqCB(QueryIqHandler), null );
}
/// <summary>
/// 处理查询结果
/// </summary>
/// <param name="sender"></param>
/// <param name="iq"></param>
/// <param name="data"></param>
private void QueryIqHandler(object sender ,IQ iq, object data)
{
if(iq.Type == IqType.result)
{
DiscoItems items = iq.SelectSingleElement<DiscoItems>();
foreach(DiscoItem item in items.GetDiscoItems())
{
//roomJid = item.Jid.Bare;
//memberNick = item.Jid.Resource;
//other process...
}
}
}
记录XMPP学习过程....
来源:oschina
链接:https://my.oschina.net/u/220228/blog/134204