Строфа не вызывает iq addHandler с помощью javascript

Я работаю над приложением, которое соединяется с XMPP openfire с помощью Strofejs. Проблема в том, что присутствие отправляется правильно, но обработчик iq никогда не вызывается. Я проверил консоль в браузерах, но ошибок не нашел.

Я хочу отправить присутствие и отправить iq, чтобы клиенты вошли в систему в клиентских сеансах openfire (автоматическое закрытие сеанса в течение 10 секунд).

Вот мой js:

function onConnect(status) {
debugger;
if (status == Strophe.Status.CONNECTING) {
    alert('Strophe is connecting.');
    log('Strophe is connecting.');
} else if (status === Strophe.Status.AUTHENTICATING) {
    alert ('status AUTHENTICATING');
} else if (status === Strophe.Status.AUTHFAIL) {
    alert ('status AUTHFAIL');
} else if (status === Strophe.Status.ATTACHED) {
  alert ('status ATTACHED');
} else if (status == Strophe.Status.CONNFAIL) {
    alert('Strophe failed to connect.');
    log('Strophe failed to connect.');
} else if (status == Strophe.Status.DISCONNECTING) {
    alert('Strophe is disconnecting.');
    log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
    alert('Strophe is disconnected.');
    log('Strophe is disconnected.');
    reConnectTimer = setInterval(reConnect, 3000);
} else if (status == Strophe.Status.CONNECTED) {
    connection.addHandler(onOwnMessage, null, 'iq', 'set', null, null);
    connection.addHandler(onMessage, null, 'message', null, null, null);
    connection.addHandler(on_presence, null, 'presence', null, null, null);
    connection.send($pres().tree());

    var pres = $pres({ to: '[email protected]/' + Math.random() });
    connection.send(pres);

    alert('Strophe is connected.');
    log('Strophe is connected.');

    clearInterval(reConnect);
    //connection.disconnect();
   }
}

function onOwnMessage(msg) {
debugger;
//  console.log(msg);
alert('msg is: ' + msg);
var elems = msg.getElementsByTagName('own-message');
if (elems.length > 0) {
    var own = elems[0];
    var to = $(msg).attr('to');
    var from = $(msg).attr('from');
    var iq = $iq({
        to: from,
        type: 'error',
        id: $(msg).attr('id')
    }).cnode(own).up().c('error', { type: 'cancel', code: '501' })
    .c('feature-not-implemented', { xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas' });
    connection.sendIQ(iq);
    alert(iq);
}
return true;
}

Пожалуйста, скажите мне, что я делаю неправильно? Я пробовал и гуглил, но я все еще не могу решить.

Заранее спасибо.


person Zia Ul Mustafa    schedule 06.11.2015    source источник


Ответы (1)


Ваш код взят из https://gist.github.com/RudyLu/5641350, который является пример кода использования Strophe.js для подключения к чату facebook. Я думаю, вы бы создали простой чат на основе вашего собственного сервера XMPP (например, используя Openfire, как указано в тегах в вашем сообщении). в этом случае вам не нужен обработчик IQ:

connection.addHandler(onOwnMessage, null, 'iq', 'set', null, null)

Обработчиков onMessage и on_presence достаточно, и они могут быть похожи на следующий код:

function onMessage(msg) {
    var to = msg.getAttribute('to');
    var from = msg.getAttribute('from');
    var type = msg.getAttribute('type');
    var elems = msg.getElementsByTagName('body');

    if (type == "chat" && elems.length > 0) {
        var body = elems[0];
        console.log('CHAT: I got a message from ' + from + ': ' + Strophe.getText(body));
    }
    // we must return true to keep the handler alive.  
    // returning false would remove it after it finishes.
    return true;
}

function on_presence (presence){
    console.log('onPresence:');
    var presence_type = $(presence).attr('type'); // unavailable, subscribed, etc...
    var from = $(presence).attr('from'); // the jabber_id of the contact
    console.log('   >'+from+' --> '+presence_type);
    if (presence_type != 'error'){
        if (presence_type === 'unavailable'){
          // Mark contact as offline
        }else{
          var show = $(presence).find("show").text(); // this is what gives away, dnd, etc.
          if (show === 'chat' || show === ''){
            // Mark contact as online
          }else{
            // etc...
          }
        }
    }
    return true;
}

Вот пример функций отправки сообщений и изменения статуса присутствия:

function sendMessage(msg, to) {
    console.log('CHAT: Send a message to ' + to + ': ' + msg);
    var m = $msg({to: to, from: connection.jid, type: 'chat'}).c("body").t(msg);
    connection.send(m);
}

function setStatus(s) {
    console.log('setStatus: '+s);
    var status = $pres().c('show').t(s);
    connection.send(status); 
}
person beaver    schedule 20.11.2015
comment
Спасибо @beaver за руководство. Сейчас изучаю XMPP, Strophe; вот почему я столкнулся с такими проблемами ... Не могли бы вы рассказать мне о «iq» в strophe.? я запутался в этом - person Zia Ul Mustafa; 07.09.2016