在线和离线用户实时使用strophe.js

时间:2016-08-17 05:16:09

标签: javascript xmpp openfire strophe bosh

我正在使用 strophe.js javascript客户端库,使用以下代码连接 xmpp 服务器( openfire )。

var BOSH_SERVICE = 'http://127.0.0.1:7070/http-bind/';
 connection = new Strophe.Connection(BOSH_SERVICE);

  connection.connect("jid",
                   "password",
                   onConnect);

和回调函数(onConnect)如下:

function onConnect(status)
{
    if (status == Strophe.Status.CONNECTING) {
    log('Strophe is connecting.');
    } else if (status == Strophe.Status.CONNFAIL) {
    log('Strophe failed to connect.');
    $('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.DISCONNECTING) {
    log('Strophe is disconnecting.');
    } else if (status == Strophe.Status.DISCONNECTED) {
    log('Strophe is disconnected.');
    $('#connect').get(0).value = 'connect';
    } else if (status == Strophe.Status.CONNECTED) {
    log('Strophe is connected.');
    log('ECHOBOT: Send a message to ' + connection.jid + 
        ' to talk to me.');

    connection.addHandler(onMessage, null, 'message', null, null,  null); 
    connection.send($pres().tree());
    console.log($pres().tree());

    }
}

我使用此代码成功连接到服务器,没问题,直到

问题:实时更新具有状态的用户列表。

让我解释一下我的问题:

我想显示实时更新的在线和离线用户列表。(类似于显示聊天应用程序。)

离。假设有3个用户A,B和C.并且所有用户都在线(登录)

现在假设用户A断开连接或脱机,那么用户B,C如何获得用户A的状态通知?并将用户A的状态更改为脱机而不刷新用户B和C列表。

strophe.js中是否有任何方法会在某个连接或断开连接时自动调用。或者我应该自己写吗?

我不确定但名单上有什么内容。

1 个答案:

答案 0 :(得分:5)

您可以使用此Strophe API为您的好友订阅状态:

connection.send($pres({
  to: jid,     // buddy jid
  type: "subscribe"
}));

实现XMPP规范(有关详细信息,请参阅https://xmpp.org/rfcs/rfc3921.html#int)。 好友可以接受订阅回复:

connection.send($pres({
  to: from,  // jid of subscriber
  type: "subscribed"
}));

您可以在Plunker上查看基于XMPP(使用Strophe.js)的Web客户端示例:

http://plnkr.co/edit/EhQHDsYpDhrECmaaIlZO

相关问题