在单个Javascript函数中处理多个websocket订阅,但只处理一个连接对象

Jim*_*mbo 1 javascript websocket promise autobahn

注意:我将Autobahn.js用于客户端WAMP实现,而when.js用于promises.

我正在尝试创建可重用的代码,以便只存在一个websocket'session'或连接,并且只要dev想要使用autobahn订阅主题,他们就可以使用当前连接对象来执行此操作存在; 否则会创建一个新的.

我的问题是,如果连接已经存在,我必须使用a setTimeout()等待一秒钟以确保它实际连接,然后复制所有订阅代码 - 我根本不喜欢这个.

这是我目前的代码:

(function() {
    var connection = null;

    subscribeTo('subject', __userId, __token, function(onconnect) {
        console.log('Yay, connected');
    });

    function subscribeTo(subject, userId, token, onConnect, onDisconnect) { 
        if (connection === null)
        {   
            connection = new ab.Session('ws://localhost:8080', function(onopen) {

                connection.subscribe(JSON.stringify({subject: subject, userId: userId, token: token}), function(subscription, data) {
                    data = $.parseJSON(data);

                    // Do something with the data ...
                });

                if (typeof onConnect === 'function') { 
                    onConnect(); 
                }

            }, function(onclose) {
                if (typeof onDisconnect === 'function') { 
                    onDisconnect(); 
                }
            }, { 'skipSubprotocolCheck': true });
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

大.现在问题是,如果我subscribeTo()在前一个之后又有另一个直接怎么办?连接将不再存在null,但也不会连接.所以我要做的就是:

// subscribeTo() multiple times at the top ...

subscribeTo('subject', __userId, __token, function(onconnect) {
    console.log('Yay, connected');
});

subscribeTo('anothersubject', __userId, __token, function(onconnect) {
    console.log('Yay, connected');
});

// The first one works, the second one requires a setTimeout() for the connection

// if connection is NOT null...
} else {
    setTimeout(function() {
        connection.subscribe(topic... etc...) // Really!?
    }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

删除setTimeout(),你会收到一个错误,说"Autbahn没有连接".

有没有更好的方法来获得单一的,可重复使用的连接,没有代码重复,或者我注定要为每个订阅创建一个新的连接,因为承诺(也许我可以在这里使用promises,尽管我没有在此之前没用过它们?

obe*_*tet 5

这太复杂,不必要和错误.你想做你的subscribes以响应正在创建的会话:

var session = null;

function start() {
   // turn on WAMP debug output
   //ab.debug(true, false, false);

   // use jQuery deferreds instead of bundle whenjs
   //ab.Deferred = $.Deferred;

   // Connect to WAMP server ..
   //
   ab.launch(
      // WAMP app configuration
      {
         // WAMP URL
         wsuri: "ws://localhost:9000/ws",
         // authentication info
         appkey: null, // authenticate as anonymous
         appsecret: null,
         appextra: null,
         // additional session configuration
         sessionConfig: {maxRetries: 10, sessionIdent: "My App"}
      },
      // session open handler
      function (newSession) {
         session = newSession;
         main();
      },
      // session close handler
      function (code, reason, detail) {
         session = null;
      }
   );
}

function main() {
   session.subscribe("http://myapp.com/mytopic1", function(topic, event) {});
   session.subscribe("http://myapp.com/mytopic2", function(topic, event) {});
   session.subscribe("http://myapp.com/mytopic3", function(topic, event) {});
}

start();
Run Code Online (Sandbox Code Playgroud)

ab.launch助手将管理自动重新连接你(如果需要的话也做WAMP-CRA认证).init()然后在重新连接时再次自动调用.Session建议不要使用原始对象(除非您知道自己在做什么).

另外:topics必须是来自httphttps方案的URI .不允许使用序列化对象(JSON).