Call specific client from SignalR

asp.netSignalr

asp.net Problem Overview


I want to call specific client from server, and not broadcast to all of them. Problem is that I'm in scope of some AJAX request (in .aspx codebehind let say), and not in Hub or PersistentConnection, so don't have Clients property - and client who made that ajax (jquery) call is not the client I want to send signalr message!

Now, I have one hub that it's called on JS page load, which registers new client into server static list, so I have client Guids. But don't know how to use that to send message from server to specific client.

asp.net Solutions


Solution 1 - asp.net

Solution 2 - asp.net

$('#sendmessage').click(function () {
    // Call the Send method on the hub. 
    chat.server.send($('#displayname').val(), $('#message').val(), $.connection.hub.id);
    // Clear text box and reset focus for next comment. 
    $('#message').val('').focus();
});

at server side send the id of the client and response to that id

  public void Send ( string name , string message , string connID )
  {
        Clients.Client(connID).broadcastMessage(name , message);
  }

Solution 3 - asp.net

Every time you send a request to the hub server, your request will have a different connection id, so, I added a static hash table that contains a username- which is not changing continuously, and a connection id fro the signal r,every time you connect, the connection id will be updated

 $.connection.hub.start().done(function () {
   chat.server.registerConId($('#displayname').val());
 });

and in the server code:

public class ChatHub : Hub
{
    private static Hashtable htUsers_ConIds = new Hashtable(20);
    public void registerConId(string userID)
    {
        if(htUsers_ConIds.ContainsKey(userID))
            htUsers_ConIds[userID] = Context.ConnectionId;
        else
            htUsers_ConIds.Add(userID, Context.ConnectionId);
    }
}

Solution 4 - asp.net

when you want to send a message to specific id

 Clients.Client(Context.ConnectionId).onMessage(
               new Message{From = e.Message.From, Body = e.Message.Body}
               );

Solution 5 - asp.net

If the specific user actually is the caller it self, you can use:

Clients.Caller.myJavaScriptClientFunction();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHrvoje HudoView Question on Stackoverflow
Solution 1 - asp.netdavidfowlView Answer on Stackoverflow
Solution 2 - asp.netuser2201030View Answer on Stackoverflow
Solution 3 - asp.netNada N. HantouliView Answer on Stackoverflow
Solution 4 - asp.netbilalView Answer on Stackoverflow
Solution 5 - asp.netradbyxView Answer on Stackoverflow