使用Strophe.js解析XML Websocket响应 [英] Parsing XML websocket responses with Strophe.js

查看:251
本文介绍了使用Strophe.js解析XML Websocket响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Strophe.js通过websockets连接到XMPP服务器。这是当连接的用户收到消息时得到的示例响应:

I'm using Strophe.js to connect to an XMPP server via websockets. Here's a sample response I get when the connected user receives a message:

<message xmlns='jabber:client' xml:lang='en' to='agent@chat.domain.com/6665193359253278721998' from='client@chat.domain.com/Mac' type='chat' id='purple42fccc5c'> 
  <archived by='agent@chat.domain.com' id='1557026681122740' xmlns='urn:xmpp:mam:tmp'/>
  <stanza-id by='agent@chat.domain.com' id='1557026681122740' xmlns='urn:xmpp:sid:0'/>
  <active xmlns='http://jabber.org/protocol/chatstates'/> 
  <body>
    1
  </body>
</message>

检查了文档,但是我找不到关于此主题的任何有用信息。 Strophe是否有内置方法从不同类型的消息中提取我需要的数据?还是我需要其他东西?

Checked the docs, but I was unable to find anything useful on the subject. Does Strophe have a built-in way to extract the data I need from different types of messages? Or do I need something else?

推荐答案

创建连接后,您需要定义钩子以接收消息并能够与之交互:

Once the connection is created you need to define hooks to receive the message and be able to interact with it:

connection.addHandler(onMessage, null, 'message', 'chat');
connection.addHandler(onMessage, null, 'message', 'groupchat');

然后,您只需要定义 onMessage

And then, you just need to define the onMessage function.

onMessge: function(stanza) {
  $stanza = $(stanza);

  messageId = $stanza.attr('id') || null;
  to = $stanza.attr('to');
  from = $stanza.attr('from').toLowerCase();
  barejid = Strophe.getBareJidFromJid(from);

  type = $stanza.attr('type');
  bodies = $stanza.find('body');
  body = bodies.length ? Strophe.xmlunescape(Strophe.getText(bodies[0])) : '';
....

}

希望有帮助。

这篇关于使用Strophe.js解析XML Websocket响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆