Call specific client from SignalR

前端 未结 5 1054
孤独总比滥情好
孤独总比滥情好 2020-11-30 22:07

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 Hu

相关标签:
5条回答
  • 2020-11-30 22:50
    $('#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);
      }
    
    0 讨论(0)
  • 2020-11-30 22:55

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

    Clients.Caller.myJavaScriptClientFunction();
    
    0 讨论(0)
  • 2020-11-30 22:56

    See the docs for the latest:

    Persistent connections - https://github.com/SignalR/SignalR/wiki/PersistentConnection

    Hubs - http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server

    0 讨论(0)
  • 2020-11-30 22:58

    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);
        }
    }
    
    0 讨论(0)
  • 2020-11-30 23:03

    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}
                   );
    
    0 讨论(0)
提交回复
热议问题