如何在成功连接时获得正确的Strophe.js回调

时间:2013-10-11 13:59:20

标签: javascript

我正在开发一个通用库,用于通过BOSH服务与xmpp用户进行通信。我使用Strophe.js

我无法理解为什么在课堂上BoshCommunicator方法onConnect我有一个Strophe对象,但没有像预期的那样BoshCommunicator。

当我在console.log(这个)时,我得到了对象{service =“http:// myboshim / http-bind”,jid =“aivaras37 @ myboshim / 29785298701381498988721337”,rid = 4092107607,more ...}

此外,在建立连接之前,我为BoshCommunicator类设置了listener属性。当我在console.log(this.listener)中我得到了未定义,但是如果我在connect()方法中调用console.log(this.listener),我会得到预期的侦听器对象转储。你能解释一下如何在BoshCommunicator.prototype.onConnect()中获得初始化的BoshCommunicator吗?另外请解释为什么我松开了我的物体并改为使用Strophe。

这是我使用的特定代码:


function BoshCommunicator(boshUri, host)
{
    this.connection = null;
    this.boshUri = null;
    this.host = null;
    this.listener = null;
    this.setBoshUri(boshUri);
    this.setHost(host);
}

BoshCommunicator.prototype.setBoshUri = function(boshUri)
{
    this.boshUri = boshUri;
};

BoshCommunicator.prototype.setHost = function(host)
{
    this.host = host;
};

BoshCommunicator.prototype.setListener = function(listener)
{
    this.listener = listener;
    this.listener.setListenHost(this.host);
};

BoshCommunicator.prototype.connect = function(jid, jpass)
{
    this.connection = new Strophe.Connection(this.boshUri);
    this.connection.connect(jid, jpass, this.onConnect);
};

BoshCommunicator.prototype.onConnect = function(status)
{
    if (status === Strophe.Status.CONNECTED) {
        console.log("Send me messages!");
        console.log(this); // dumps strophe object. Paste from console: Object { service="http://myboshim/http-bind", jid="aivaras37@myboshim/29785298701381498988721337", rid=4092107607, more...}
        console.log(this.listener); // undefined - how come?
        this.connection.addHandler(this.listener.onReceivedMessage, null, 'message', null, null,  null);
        this.connection.send($pres().tree());
    }
};

function MessageListener()
{
    this.host = null;
}

MessageListener.prototype.setListenHost = function(host)
{
    this.host = host;
};

function ReceivedMessageNotify()
{
    MessageListener.call(this);
}

ReceivedMessageNotify.prototype = new MessageListener();
ReceivedMessageNotify.prototype.constructor = ReceivedMessageNotify;
ReceivedMessageNotify.prototype.onReceivedMessage = function(message)
{
    console.log(message);
    var elems = message.getElementsByTagName('body');
    var body = elems[0];
    if (Strophe.getText(body).length > 0) {
        this.sendNewMessageNotify(message.getAttribute('from'), Strophe.getText(body));
    }
    return true;
};

ReceivedMessageNotify.prototype.sendNewMessageNotify = function(sender, messageBody)
{
    alert("New message: " + sender + " wrote: " + messageBody);
};

$(document).ready(function() {
    var communicator = new BoshCommunicator('http://myboshim/http-bind', 'myboshim');
    communicator.setListener(new ReceivedMessageNotify());
    communicator.connect('jabberId', 'accPasswd');
});

1 个答案:

答案 0 :(得分:1)

查看下面提到的以下代码:

使用说明:



var demo = DEMOPROJECT.Xmpp.init();
demo.connction.connect(username, password, function() {
    //success callback

}, function() {
    //errror callback

});






(function(MODULE) {

    "use strict";

    MODULE.Xmpp = function() {

        var _self;
        function _getInstance(xmpp_bosh_url) {
            try {
                return new Strophe.Connection(xmpp_bosh_url);
            } catch (e) {
                _self.log("Strophe Connection Failed: " + e.message);
            }
        };
        function _onConnect(status, callback, errorCallback) {
            var error = '';
            switch (status) {
                case Strophe.Status.ERROR:
                    error = "Error: " + Strophe.Status.ERROR;
                    break;
                case Strophe.Status.CONNECTING:
                    _self.log('Connecting...');
                    break;
                case Strophe.Status.CONNFAIL:
                    error = "Connection Failed: " + Strophe.Status.ERROR;
                    break;
                case Strophe.Status.AUTHENTICATING:
                    _self.log('Authenticating client...');
                    break;
                case Strophe.Status.AUTHFAIL:
                    error = "Authorization Fail: " + Strophe.Status.AUTHFAIL;
                    break;
                case Strophe.Status.CONNECTED:
                    _self.log('Connected...');
                    _onConnected(callback);
                    break;
                case Strophe.Status.DISCONNECTING:
                    _self.log('Diconnecting...');
                    break;
                case Strophe.Status.DISCONNECTED:
                    _self.log('Diconnected...');
                    break;
                case Strophe.Status.ATTACHED:
                    _self.log('Attached...');
                    break;
            }
            if (error) {
                _onError(errorCallback, status, error);
            }
            return true;
        };
        function _onError(errorCallback, errorCode, error) {
            _self.disconnect();
            (typeof errorCallback == 'function') ? errorCallback.call(this, errorCode, error): '';
        };
        function _onConnected(callback) {
            (typeof callback == 'function') ? callback.call(this): '';
        };

        return {
            init: function(xmpp_bosh_url) {
                _self = this;
                if (!_self.connection) {
                    _self.connection = _getInstance(xmpp_bosh_url);
                    if (MODULE.config.debug) {
                        this.debugInfo("html");
                    }
                    return _self;
                }
                return _self;
            },
            connect: function(userName, password, callback, errorCallback) {
                _self.userName = userName;
                _self.password = password;
                this.connection.connect(userName, password, function(status) {
                    _onConnect(status, callback, errorCallback);
                });
            },
            isConnected: function() {
                return _self.connection.connected;
            },
            getType: function() {
                return _self.connection.servtype;
            },
            getDomain: function() {
                return _self.connection.domain;
            },
            sendMessage: function(message) {
                if (!message) {
                    return false;
                } else {
                    this.connection.sendIQ(message.tree(), function(data) {
                        console.log("message success");
                    }, function(err) {
                        console.log("message errror");
                    });
                }
            },
            removeListener: function(listener) {
                this.connection.deleteHandler(listener);
            },
            disconnect: function() {
                if (this.connection !== null) {
                    this.connection.disconnect();
                    this.connection.flush();
                    this.connection = null;
                }
            },
            debugInfo: function(stream) {
                console.log(message);
            }
        }
    }();

    
})(window.DEMOPROJECT = window.DEMOPROJECT || {});


var demo = DEMOPROJECT.Xmpp.init();
demo.connction.connect(username, password, function() {
    //success callback

}, function() {
    //errror callback

});