Reputation: 12932
I have followed this tutorial religiously in order to add an ASP.NET MVC SignalR chat page on a bare-bones ASP.NET MVC 4 template project. Instead of using the following method from the tutorial to have a user send a message to all other users:
public void Send(string name, string message)
{
Clients.All.addNewMessageToPage(name, message);
}
I have created my own, as follows:
public void Send(string senderName, string recipientName, string message)
This variant allows users to send messages to explicitly named other users that are in the chat room (my users must be logged in to chat). Since the user gets to pass in the recipient's name, how can I find the Client that corresponds to that user name? In other words, how can I find the logged in ApplicationUser that has that UserName from my Send
method?
Upvotes: 0
Views: 2165
Reputation: 2840
You can indeed map users to connection IDs, and that may also be preferable in some cases, however, when you want to invoke a function for a particular user, you can also use the User(string userId)
method, which exists on your Clients property in your hub:
public void Send(string senderName, string recipientName, string message)
{
Clients.User(recipientName).addNewMessageToPage(senderName, message);
}
Note that, while the parameter name for this method is "userId", you should pass in the user name here. That surprised me, when I first used this method.
This feature is only available in SignalR 2.0+, see here for more details, including other methods of keeping track of connected users in your SignalR hub..
Upvotes: 4