信号r存储Context.connectionID
问题描述:
我是新来signalr,我想生成连接ID到特定的客户端,并将其存储在数据库中,一旦任何客户端完成任何更新将通知所有,但它是好的做法将context.connectionID存储到数据库中,如果不是,我想知道所有客户端之间的连接需要帮助。信号r存储Context.connectionID
答
当客户端调用服务器端的功能时,您可以通过Context.ConnectionId
检索其连接ID。现在,如果您想通过集线器之外的机制访问该连接Id,您可以:
只需让Hub调用传入连接ID的外部方法即可。 添加到OnConnected
字典中,并将其从OnDisconnected
中删除。一旦你有你的用户列表,你可以通过你的外部机制来查询它。
Ex 1:
public class MyHub : Hub
{
public void AHubMethod(string message)
{
// Send the current clients connection id to your external service
MyExternalSingleton.InvokeAMethod(Context.ConnectionId);
}
}
EX : 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()
{
MyUserType garbage;
MyUsers.TryRemove(Context.ConnectionId, out garbage);
return base.OnDisconnected();
}
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
@does connectionID会一直改变客户端重新连接..? –