如何在服务器端获取signalR客户端的连接ID?

我需要获取客户端的连接ID。 我知道你可以使用$.connection.hub.id从客户端获得它。 我需要的是在networking服务中进入,我有哪些更新logging在数据库中,反过来在网页上显示更新。 我是新的signalR和计算器,所以任何意见,将不胜感激。 在我的客户网页上,我有这样的:

 <script type="text/javascript"> $(function () { // Declare a proxy to reference the hub. var notify = $.connection.notificationHub; // Create a function that the hub can call to broadcast messages. notify.client.broadcastMessage = function (message) { var encodedMsg = $('<div />').text(message).html();// Html encode display message. $('#notificationMessageDisplay').append(encodedMsg);// Add the message to the page. };//end broadcastMessage // Start the connection. $.connection.hub.start().done(function () { $('#btnUpdate').click(function () { //call showNotification method on hub notify.server.showNotification($.connection.hub.id, "TEST status"); }); }); });//End Main function </script> 

一切工作,直到我想使用signalR更新页面。 我的集线器中的显示通知function是这样的:

 //hub function public void showNotification(string connectionId, string newStatus){ IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>(); string connection = "Your connection ID is : " + connectionId;//display for testing string statusUpdate = "The current status of your request is: " + newStatus;//to be displayed //for testing, you can display the connectionId in the broadcast message context.Clients.Client(connectionId).broadcastMessage(connection + " " + statusUpdate); }//end show notification 

我怎么能发送connectionid到我的networking服务?

希望我不想做一些不可能的事情。 提前致谢。

当客户端调用服务器端的一个函数时,可以通过Context.ConnectionId检索它们的连接ID。 现在,如果您想通过集线器之外的机制访问该连接ID,您可以:

  1. 只需让Hub调用传入连接ID的外部方法即可。
  2. 通过添加到OnConnected的字典并在OnDisconnected从其中删除,pipe理连接的客户端的列表(又名public static ConcurrentDictionary<string, MyUserType>... 。 一旦你有你的用户列表,你可以通过你的外部机制来查询。

例1:

 public class MyHub : Hub { public void AHubMethod(string message) { MyExternalSingleton.InvokeAMethod(Context.ConnectionId); // Send the current clients connection id to your external service } } 

例2:

 public class MyHub : Hub { public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>(); public override Task OnConnected() { MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId }); return base.OnConnected(); } public override Task OnDisconnected(bool stopCalled) { MyUserType garbage; MyUsers.TryRemove(Context.ConnectionId, out garbage); return base.OnDisconnected(stopCalled); } public void PushData(){ //Values is copy-on-read but Clients.Clients expects IList, hence ToList() Clients.Clients(MyUsers.Keys.ToList()).ClientBoundEvent(data); } } public class MyUserType { public string ConnectionId { get; set; } // Can have whatever you want here } // Your external procedure then has access to all users via MyHub.MyUsers 

希望这可以帮助!

我要求在重新连接上有所不同。 客户留在列表中,但连接将会改变。 我对重新连接上的静态列表进行更新以解决此问题。