Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SignalR - multiple hubs - start connections individually

I have a SignalR application which has multiple hubs (the hubs are part of different projects inside the same solution).

In the front-end I want to start connections based on the component a user is currently viewing.

Let's assume I have 2 hubs and 2 components: TestHub1, TestHub2; Component1, Component2.

In each component I instantiate the connection as following:

var testHub = $.connection.testHub;

            //define client methods

            $.connection.hub.logging = true;
            $.connection.hub.start();
        });

So I do this in multiple components. Now, assuming I have both components connected to TestHub1 and TestHub2 respectively (at the same time), how can I only stop one connection? If in any component I call $.connection.hub.stop(), both hub connections are stopped.

How can I start and stop the hub connections individually? (Because if at one point after I have stopped both of them and I call $.connection.hub.start(), even if I call this from the component which uses TestHub1, TestHub2 will also start the connection.

So I am looking for a way to start and stop individual hub connections rather that the entire $.connection.start() and $.connection.hub.stop().

Thanks!

like image 876
radu-matei Avatar asked Sep 25 '15 07:09

radu-matei


1 Answers

Default generated proxy class creates one connection for all hubs. So you can have multiple hubs sharing one connection on your site. But all Hubs get the same HTTP request information. http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server#multiplehubs

Since all Hubs share the same connection, the only HTTP request information that the server gets is what comes in the original HTTP request that establishes the SignalR connection. If you use the connection request to pass information from the client to the server by specifying a query string, you can't provide different query strings to different Hubs. All Hubs will receive the same information.

To manage connections for each hub manualy you need to implement proxy by yourself:

    var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');
contosoChatHubProxy.on('addContosoChatMessageToPage', function(name, message) {
    console.log(name + ' ' + message);
});
connection.start().done(function() {
    // Wire up Send button to call NewContosoChatMessage on the server.
    $('#newContosoChatMessage').click(function () {
        contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val());
        $('#message').val('').focus();
                });
    });

Please look here to find out more details http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#getproxy

like image 53
Yuriy A. Avatar answered Nov 03 '22 22:11

Yuriy A.