SignalR client with multiple connections

前端 未结 2 1422
名媛妹妹
名媛妹妹 2020-12-23 12:47

I have multiple SignalR \'services\' running and only one UI to access them.

How can I make the client js to talk to multiple connections with different Url? Because

相关标签:
2条回答
  • 2020-12-23 13:05

    $.connection.hub is created in the /signalr/hubs inclusion.

    At the end of the file it essentially does:

    $.connection.hub = $.hubConnection("/signalr", { useDefaultPath: false });
    

    To create the hub proxy you do:

    var myHub = $.connection.hub.createHubProxy('myHub');
    

    Simple example for multiple connections:

    var connection1 = $.hubConnection("http://www.myfirstendpoint.com");
    var connection2 = $.hubConnection("http://www.mysecondendpoint.com");
    
    var myCon1Hub = connection1.createHubProxy('myCon1Hub');
    var myCon2Hub = connection2.createHubProxy('myCon2Hub');
    
    myCon1Hub.client.foo = function() { ... Whatever you want ... };
    myCon2Hub.client.foo = function() { ... Whatever you want ... };
    
    connection1.start();
    connection2.start();
    
    0 讨论(0)
  • 2020-12-23 13:20

    My solution for such occasions:

    var SignalRHelpers = function () {
      var _connectionDeferred;
    
      var subscribeToConnectionStart = function (callback) {
        if (!_connectionDeferred)   // start connection if not yet initialized
            _connectionDeferred = $.connection.hub.start();
    
        if ($.connection.hub.state == $.connection.connectionState.connected && callback) {
            // already connected
            callback();
        } else if (callback) {
            // register handler
            _connectionDeferred.done(callback);
        }
      };
    
      return {
        SubscribeToConnectionStart: subscribeToConnectionStart
      };
    }();
    

    It internally stores the promise object from start() and attaches handlers as needed.

    Basically you just call SignalRHelpers.SubscribeToConnectionStart every time you need to connect. For example

    SignalRHelpers.SubscribeToConnectionStart(function(){
        someHub.server.executeSomething();
    });
    
    0 讨论(0)
提交回复
热议问题