Call a specific client from SignalR

I want to call a specific client from the server and not broadcast it to everyone. The problem is that I go into the scope of some AJAX request (in .aspx codebehind let say), and not in the Hub or PersistentConnection, therefore it does not have the Clients property - and the client who made this ajax (jquery) call is not a client I I want to send an alarm message!

Now I have one hub that he called to load the JS page, which registers the new client in the static list of servers, so I have client guides. But I don’t know how to use this to send a message from the server to a specific client.

+54
signalr
Oct 24 2018-11-11T00:
source share
5 answers
+44
Oct 24 2018-11-11T00:
source share
$('#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(); }); 

on the server side sends the client identifier and responds to this id

  public void Send ( string name , string message , string connID ) { Clients.Client(connID).broadcastMessage(name , message); } 
+15
Mar 22 '13 at 22:14
source share

Each time you send a request to the hub server, your request will have a different connection identifier, so I added a static hash table containing a username that does not change continuously, and a connection identifier for signal r, every time you connect , the connection identifier will be updated

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

and in 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); } } 
+10
Aug 31 '14 at 12:24
source share

If a particular user is actually the caller, you can use:

 Clients.Caller.myJavaScriptClientFunction(); 
+1
Mar 28 '16 at 16:10
source share

when you want to send a message to a specific id

  Clients.Client(Context.ConnectionId).onMessage( new Message{From = e.Message.From, Body = e.Message.Body} ); 
0
Oct 27 '16 at 5:02
source share



All Articles