Search code examples
signalrsignalr-hub

Are SignalR connectionIDs hub-specific?


If I have several hubs, and connect a single JavaScript client to all of them, will the context ConnectionID be the same between them?


Solution

  • Interesting question. I didn't know the answer, so I tested it using this example by changing it a bit.

    The Hub classes:

    public class ChatHub : Hub {
        public void Send(string name, string message) {
            string cid = Context.ConnectionId;
            Clients.All.sendMessage(name, message);
        }
    }
    
    public class ChatHub2 : Hub
    {
        public void Send(string name, string message)
        {
            string cid = Context.ConnectionId;
            Clients.All.sendMessage(name, message);
        }
    }
    

    The page.html connecting to the hubs:

    var chat = $.connection.chatHub;
    var chat2 = $.connection.chatHub2;
    $.connection.hub.start().done(function () {
        // Call the Send method on the hub.
        chat.server.send('Me', 'Message to 1');
        chat2.server.send('Me', 'Message to 2');
    });
    

    I set breakpoints on the Hub methods and both are called, and Context.ConnectionId are the same. That's what I was expecting. Give it a try!

    It makes sense, it supposed to use the same connection to send the message over.