从 SignalR 调用特定客户端

我希望从服务器调用特定的客户端,而不是向所有客户端广播。问题是,我在某个 AJAX 请求的范围内(在。Aspx 代码隐藏) ,而不是在 Hub 或 PersisentConnection,所以没有客户端属性-和客户端谁做了 ajax (jquery)调用不是客户端我想发送信号消息!

现在,我有一个在 JS 页面加载时调用的集线器,它将新客户端注册到服务器静态列表中,因此我有客户端 Guids。但不知道如何使用它从服务器发送消息到特定的客户端。

95571 次浏览
$('#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);
}

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);
}
}

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

Clients.Caller.myJavaScriptClientFunction();

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}
);