anthonypliu
anthonypliu

Reputation: 12437

Anyway to post message from hub class to another hub's javascript handler function

I have 2 hub classes: hubA and hubB.

In hubA I have a function that performs a task :

public void doSomething(string test){
    Clients[Context.ConnectionId].messageHandler(test);
}

I do not want this function to post back to hubA.messageHandler = function(){...} I want to be able to post a message back to hubB.messageHandler = function(){...}, but I am calling it from inside my hubA hub class. Is this possible?

Upvotes: 0

Views: 123

Answers (1)

Drew Marsh
Drew Marsh

Reputation: 33379

If both hubs are hosted in the same application you should just be able to use:

GlobalHost.ConnectionManager.GetHubContext<HubB>()

Now the trick is, you appear to want to send a message to a specific client on HubB and the problem is that Context.ConnectionId for HubA will not be the same id for HubB. So what you need to do is have a mapping of some kind from ConnectionId to logical a user of some kind in both HubA and HubB. Then when you need to "bridge the gap" you do a lookup of the logical user from HubA by HubA's ConnectionId and then find the ConnectionId for HubB. At that point your code could look like this:

public void DoSomething(string test)
{ 
    // Get HubB's ConnectionId given HubA's ConnectionId (implementation left to you)
    string hubBConnectionId = MapHubAConnectionIdToHubBConnectionId(Context.ConnectionId);

    // Get the context for HubB
    var hubBContext = GlobalHost.ConnectionManager.GetHubContext<HubB>();

    // Invoke the method for just the current caller on HubB
    hubBContext.Clients[hubBConnectionId].messageHandler(test); 
}

Upvotes: 1

Related Questions