locked
Use two hub proxies from different orgins. RRS feed

  • Question

  • User2057898579 posted

    In my web application I have the requirement to use two different signalr services.

    The first generated proxy is running on  "DomainA/signalr/hubs" and the second on "DomainB/signalr/hubs" how can I work with both generated proxies at same time?

    Tuesday, July 28, 2015 3:30 AM

All replies

  • User1644755831 posted

    Hello progi,

    Please try this.

    //$.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();
    

    Hope this helps.

    With Regards,

    Krunal Parekh

    Wednesday, July 29, 2015 5:10 AM
  • User2057898579 posted

    This works not. 

    If you call:

    var myCon1Hub = connection1.createHubProxy('myCon1Hub');

    Then you have an error that this proxy does not exists.... 

    (In my generated proxy file is see the hub).

    Are you shure that this should run? (It looks like copied from google) I have never see a solution which runs. 

    Inside jquery.signalr.js you find the following code for createHubProxy

    hubConnection.fn.createHubProxy = function (hubName) {
    /// <summary>
    /// Creates a new proxy object for the given hub connection that can be used to invoke
    /// methods on server hubs and handle client method invocation requests from the server.
    /// </summary>
    /// <param name="hubName" type="String">
    /// The name of the hub on the server to create the proxy for.
    /// </param>
    
    // Normalize the name to lowercase
    hubName = hubName.toLowerCase();
    
    var proxy = this.proxies[hubName];
    if (!proxy) {
    proxy = hubProxy(this, hubName);
    this.proxies[hubName] = proxy;
    }
    
    this._registerSubscribedHubs();
    
    return proxy;
    };

    The problem is that " this.proxies" has no entries.

    inside the first generate hub proxy is the following code for createHubProxies:

       $.hubConnection.prototype.createHubProxies = function () {
            var proxies = {};
            this.starting(function () {
                // Register the hub proxies as subscribed
                // (instance, shouldSubscribe)
                registerHubProxies(proxies, true);
    
                this._registerSubscribedHubs();
            }).disconnected(function () {
                // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
                // (instance, shouldSubscribe)
                registerHubProxies(proxies, false);
            });
    
            proxies['pviGatewayHub'] = this.createHubProxy('pviGatewayHub'); 
            proxies['pviGatewayHub'].client = { };
            proxies['pviGatewayHub'].server = {
                getSpeedHistory: function (aMachineId) {
                    return proxies['pviGatewayHub'].invoke.apply(proxies['pviGatewayHub'], $.merge(["GetSpeedHistory"], $.makeArray(arguments)));
                 },
    
                registerForMachine: function (aMachineId) {
                    return proxies['pviGatewayHub'].invoke.apply(proxies['pviGatewayHub'], $.merge(["RegisterForMachine"], $.makeArray(arguments)));
                 },
    
                unregisterForMachine: function (aMachineId) {
                    return proxies['pviGatewayHub'].invoke.apply(proxies['pviGatewayHub'], $.merge(["UnregisterForMachine"], $.makeArray(arguments)));
                 }
            };
    
            return proxies;
        };
    
        signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
        $.extend(signalR, signalR.hub.createHubProxies());

    In the second is the following code:

       $.hubConnection.prototype.createHubProxies = function () {
            var proxies = {};
            this.starting(function () {
                // Register the hub proxies as subscribed
                // (instance, shouldSubscribe)
                registerHubProxies(proxies, true);
    
                this._registerSubscribedHubs();
            }).disconnected(function () {
                // Unsubscribe all hub proxies when we "disconnect".  This is to ensure that we do not re-add functional call backs.
                // (instance, shouldSubscribe)
                registerHubProxies(proxies, false);
            });
    
            proxies['demoHub'] = this.createHubProxy('demoHub'); 
            proxies['demoHub'].client = { };
            proxies['demoHub'].server = {
                addNews: function (aTitle, aDescription) {
                    return proxies['demoHub'].invoke.apply(proxies['demoHub'], $.merge(["AddNews"], $.makeArray(arguments)));
                 },
    
                deleteNews: function (aGuid) {
                    return proxies['demoHub'].invoke.apply(proxies['demoHub'], $.merge(["DeleteNews"], $.makeArray(arguments)));
                 },
    
                getAllNews: function () {
                    return proxies['demoHub'].invoke.apply(proxies['demoHub'], $.merge(["GetAllNews"], $.makeArray(arguments)));
                 },
    
                postToast: function (aTilte, aDescription, aType) {
                    return proxies['demoHub'].invoke.apply(proxies['demoHub'], $.merge(["PostToast"], $.makeArray(arguments)));
                 }
            };
    
            proxies['languageConfigHub'] = this.createHubProxy('languageConfigHub'); 
            proxies['languageConfigHub'].client = { };
            proxies['languageConfigHub'].server = {
                changeLanguageState: function (languageKey, enabled) {
                    return proxies['languageConfigHub'].invoke.apply(proxies['languageConfigHub'], $.merge(["ChangeLanguageState"], $.makeArray(arguments)));
                 },
    
                getLanguageStates: function () {
                    return proxies['languageConfigHub'].invoke.apply(proxies['languageConfigHub'], $.merge(["GetLanguageStates"], $.makeArray(arguments)));
                 }
            };
    
            proxies['linesHub'] = this.createHubProxy('linesHub'); 
            proxies['linesHub'].client = { };
            proxies['linesHub'].server = {
                getLines: function () {
                    return proxies['linesHub'].invoke.apply(proxies['linesHub'], $.merge(["GetLines"], $.makeArray(arguments)));
                 }
            };
    
            proxies['serviceRequestHub'] = this.createHubProxy('serviceRequestHub'); 
            proxies['serviceRequestHub'].client = { };
            proxies['serviceRequestHub'].server = {
                closeRequest: function (aOpenReason, aObjectId) {
                    return proxies['serviceRequestHub'].invoke.apply(proxies['serviceRequestHub'], $.merge(["CloseRequest"], $.makeArray(arguments)));
                 },
    
                createRequest: function (aOpenReason, aObjectId) {
                    return proxies['serviceRequestHub'].invoke.apply(proxies['serviceRequestHub'], $.merge(["CreateRequest"], $.makeArray(arguments)));
                 },
    
                getServiceRequestInfo: function (aObjectId) {
                    return proxies['serviceRequestHub'].invoke.apply(proxies['serviceRequestHub'], $.merge(["GetServiceRequestInfo"], $.makeArray(arguments)));
                 },
    
                isAnyRequestOpen: function () {
                    return proxies['serviceRequestHub'].invoke.apply(proxies['serviceRequestHub'], $.merge(["IsAnyRequestOpen"], $.makeArray(arguments)));
                 }
            };
    
            return proxies;
        };

    Thursday, July 30, 2015 2:02 AM
  • User1644755831 posted

    Hello progi,

    progi

    Are you shure that this should run? (It looks like copied from google) I have never see a solution which runs. 

    Yes I did find the code as accepted answer here. http://stackoverflow.com/questions/15468662/signalr-client-with-multiple-connections

    Sorry I forgot to mention that it was not tested. As my understanding I thought this is what you needed can you please provide a sample in which this case is reproducible since they require different domains I was not able to reproduce the issue. if you provide me working links of signalr connections in which I could reproduce the issue it might help.

    Please see this: http://w3facility.org/question/signalr-client-with-multiple-connections/ it also state the same thing.

    With Regards,

    Krunal Parekh

    Thursday, July 30, 2015 2:27 AM
  • User2057898579 posted

    There you have my two files maybe you see something what I'm doing wrong. I have a running solution without generated proxies, but I like to use the generated proxies.

    Creation of "connection" to hubs on first domain

      function createHubProxies() {
    
                connection1 = $.hubConnection(hubUrl);
             
                pviHub = connection1.createHubProxy('pviGatewayHub');
    
                pviHub.client.machineUpdate =function (updatedValues) {
                    $log.debug("MachineUpdate received" + updatedValues.MachineId);
                    notifyMachineUpdatedEventInitObservers(updatedValues);
                };
    
                pviHub.client.speedValueAdded = function (historyValue) {
                    $log.debug("SpeedValue added received" + historyValue.MachineId);
                    notifySpeedValueAddedObverservers(historyValue);
                };
    
                pviHub.client.serverError = function (error) {
                    var jsonStr = JSON.stringify(error);
                    $log.debug(error);
                };
    
                connection1.start().done(function () {
                    console.log("SignalR connected");
                    signalRStarted = true;
                    initilized = true;
                    notifyServiceInitObservers();
                });
            }

    Creation of "connection" to hubs on second domain

    function createHubProxies() {
                serviceHubConnection = $.hubConnection("http://localhost:54421");
                
                // Language Hub
                // =============================================================
                languageHubProxy = serviceHubConnection.createHubProxy('languageConfigHub');
                
                languageHubProxy.client.languageStateChanged = function (language) {
                    serviceConnected = false;
                    notifyLanguageChangedObservers(language);
                };
    
                // Lines Hub
                // =============================================================
                lineHubProxy = serviceHubConnection.createHubProxy('linesHub');
    
    
                // Service Request Hub
                // =============================================================
                serviceRequestHub = serviceHubConnection.createHubProxy('serviceRequestHub');
                serviceRequestHub.client.requestInfoChanged = function (requestInfo) {
                    notifyServiceRequestInfoChanged(requestInfo);
                };
                demoHubProxy = serviceHubConnection.createHubProxy('demoHub');
                demoHubProxy.client.newsDeleted = function (id) {
                    notifyNewsDeletedObservers(id);
                };
                demoHubProxy.client.newsAdded = function (news) {
                    notifyNewsAddedObservers(news);
                };
                demoHubProxy.client.toastAdded = function (toastTitle, toastDetails, toastType) {
                    notifyToastAddedObservers(
                    {
                        title: toastTitle,
                        details: toastDetails,
                        type: toastType
                    });
    
                };
    
                // Log general signalr events.
                // =============================================================
                serviceHubConnection.reconnecting(function () {
                    $log.debug('HUB reconnecting');
                });
    
                serviceHubConnection.connectionSlow(function () {
                    $log.warn('HUB connectionSlow');
                });
    
    
                serviceHubConnection.error(function (error) {
                    $log.error('SignalR error: ' + error);
                });
    
                serviceHubConnection.disconnected(function () {
                    $log.debug('HUB disconnected');
                    setTimeout(function () {
                        serviceHubConnection.start();
                    }, 5000); // Restart connection after 5 seconds.
                });
    
    
                // Start connection.
                serviceHubConnection.logging = true;
                // =============================================================
                serviceHubConnection.start().done(function () {
                    serviceInitialized = true;
                    $log.debug('ServiceHub: Initilized ------------------');
                    if (serviceInitialized) {
                        notifyServiceInitObservers();
                    }
                }).fail(function (error) {
                    $log.error('ServiceHub: not initialized' + error);
                });
    
            }
    

    By the way if i do not use the generated proxy for the first connection it works:

        function init() {
    
                connection1 = $.hubConnection(hubUrl, { useDefaultPath: false });
    
                // Declare a proxy to reference the hub.
                pviHub = connection1.createHubProxy('PviGatewayHub');
    
                pviHub.on('MachineUpdate', function (updatedValues) {
                    $log.debug("MachineUpdate received" + updatedValues.MachineId);
                    notifyMachineUpdatedEventInitObservers(updatedValues);
                });
    
                pviHub.on('SpeedValueAdded', function (historyValue) {
                    $log.debug("SpeedValue added received" + historyValue.MachineId);
                    notifySpeedValueAddedObverservers(historyValue);
                });
    
                pviHub.on('ServerError', function (error) {
                    var jsonStr = JSON.stringify(error);
                    $log.debug(error);
                });
    
                connection1.start().done(function () {
                    console.log("SignalR connected");
                    signalRStarted = true;
                    initilized = true;
                    notifyServiceInitObservers();
        
                });
            }
    

    Thursday, July 30, 2015 2:43 AM