How Can I Send Message To specific User with signalR
You can send broadcast message to all Users without connection id. You just need to assign a Unique ID to Every user and Send it as Message parameters.
SignalR Gives a Unique ID to Every Client as connection ID. Either you can use that connection Id or you can assign unique ID to client while creating client and use it as Connection ID. thats up to you what you want to Use.
Edit
Just Update Your Your Method in your Hub Class File.....
public void Send(string name, string message, string connectionid)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message, connectionid);
}
And In Your Client Side You can Update Add Code After including SignalR Files:-
var chat = $.connection.chatHub;
chat.client.addNewMessageToPage = function (name, message, connectionid) {
if (connectionid == $('#connection').val()) {
// Do What You want Here...
};
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
$('#connection').val(prompt('Enter your ID:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val(), $('#connection').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
Hope This Helps...
If you want to send message to specific user in SignalR, easiest way is the use Form authentication. Also you can use your custom session with form authentication. Right after creation your session code put this code.
FormsAuthentication.SetAuthCookie(username.Trim(), false);
Then in signalR you can use this line for send message to this user:
var username = Context.User.Identity.Name;
context.Clients.User(username).updateMessages(message);
EDIT:
For your question pass username to this method (receiver username) and push message to that user.Then you dont need to give a userForId, because you already have sender username with "var username = Context.User.Identity.Name;".Also this method will just push to method that receiver user name. If you want to get also message to sender you need to user "Caller" and you need a write new function to get caller messages in javascript.I hope its clear for you.
public void Send(string username, string message)
{
context.Clients.Caller.updateMessagesCaller(message);
context.Clients.User(username).updateMessages(message);
}
This message will go only that username.And my recommendation is use FormAuthentication implementation in your whole project.Thanks.