javascript - Strophe.addHandler 只从响应中读取第一个节点是否正确?

标签 javascript xmpp strophe

我开始学习 strophe 库的使用,当我使用 addHandler 解析响应时,它似乎只读取 xml 响应的第一个节点,所以当我收到这样的 xml 时:

<body xmlns='http://jabber.org/protocol/httpbind'>
 <presence xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='avaliable' id='5593:sendIQ'>
  <status/>
 </presence>
 <presence xmlns='jabber:client' from='test@localhost' to='test2@localhost' xml:lang='en'>
  <status />     
 </presence>
 <iq xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='result'>
  <query xmlns='jabber:iq:roster'>
   <item subscription='both' name='test' jid='test@localhost'>
    <group>test group</group>
   </item>
  </query>
 </iq>
</body>

像这样使用处理程序 testHandler :

connection.addHandler(testHandler,null,"presence");
function testHandler(stanza){
  console.log(stanza);
}

它只记录:

<presence xmlns='jabber:client' from='test2@localhost' to='test2@localhost' type='avaliable' id='5593:sendIQ'>
 <status/>
</presence>

我错过了什么?这是正确的行为吗?我应该添加更多处理程序来获取其他节吗? 感谢提前

最佳答案

似乎是当函数 addHandler 被调用时,堆栈(包含所有要调用的处理程序的数组)在执行处理程序时被清空。所以当匹配handler条件的节点被调用时,栈被清空,其他节点就找不到了,所以你必须重新设置handler,或者像这样添加你希望被调用的handler:

 connection.addHandler(testHandler,null,"presence");
 connection.addHandler(testHandler,null,"presence");
 connection.addHandler(testHandler,null,"presence");

或:

 connection.addHandler(testHandler,null,"presence");
 function testHandler(stanza){
    console.log(stanza);
    connection.addHandler(testHandler,null,"presence");
 }

可能不是最好的解决方案,但我会一直使用,直到有人给我更好的解决方案为止,无论如何我都会发布此解决方法以提示我正在处理的代码流程。

编辑

阅读 http://code.stanziq.com/strophe/strophejs/doc/1.0.1/files/core-js.html#Strophe.Connection.addHandler 中的文档我发现这一行:

如果要再次调用处理程序,则应返回 true;返回 false 将在返回后删除处理程序。

因此只需添加一行即可修复:

 connection.addHandler(testHandler,null,"presence");
 function testHandler(stanza){
    console.log(stanza);
    return true;
 }

关于javascript - Strophe.addHandler 只从响应中读取第一个节点是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2912530/

相关文章:

javascript - 使用点分隔符对字符串的数组数量进行排序

javascript - TypeScript:在泛型约束中使用类型参数

ios - XMPPStream Connect 似乎可以工作,但委托(delegate)方法 xmppStreamDidConnect 没有被调用,为什么?

ios - 无法使用 XMPPFramework 连接到远程服务器

xmpp - 如何使用 TurnSocket (XEP-0065 : SOCKS5 Bytestreams) connection? XEP-0096 : SI File Transfer? [socket writeData]?

javascript - 如何使用 requirejs 导入 strophe?

xmpp - 为什么 XMPP 服务器忽略我的昵称订阅请求?

javascript - 为什么我的 Bootstrap 弹出窗口不起作用?

javascript - 将变量从 PHP 发送到 Javascript

XMPP:如何向服务器请求用户联系人的存在状态?