这就是我所做的:
我有一个类HubConnectionManager:
public class HubConnectionManager
{
static HubConnectionManager()
{
connections = new Dictionary<string, List<string>>();
users = new List<Login>();
}
#region Static Fields
private static Dictionary<string, List<string>> connections;
private static List<Login> users;
#endregion
#region Public Properties
public static Dictionary<string, List<string>> Connections
{
get
{
return connections;
}
}
#endregion
#region Public Methods and Operators
public static void AddConnection(Login login, string connectionId)
{
if (!connections.ContainsKey(login.LoginName))
{
connections.Add(login.LoginName, new List<string>());
if (!users.Contains(login))
{
users.Add(login);
}
}
// add with new connection id
connections[login.LoginName].Add(connectionId);
}
public static bool IsOnline(string connectionId)
{
return connections.Any(x => !string.IsNullOrEmpty(x.Value.FirstOrDefault(y => y == connectionId)));
}
public static void RemoveConnection(string user, string connectionId)
{
if (connections.ContainsKey(user))
{
connections[user].Remove(connectionId);
if (connections[user].Count == 0)
{
connections.Remove(user);
// remove user
users.RemoveAll(x => x.LoginName == user);
}
}
}
public static int GetAllConnectionsCount()
{
return connections.Keys.Sum(user => connections[user].Count);
}
public static Login GetUser(string connectionId)
{
string userName = connections.FirstOrDefault(x => x.Value.Any(y => y == connectionId)).Key;
return users.FirstOrDefault(x => x.LoginName == userName);
}
#endregion
}
我正在使用包含 UserName 及其连接列表的字典(这是因为就像您所说的,有时 OnDisconnected 无法正常触发:
connections = new Dictionary<string, List<string>>();
然后在您的集线器中,您可以检查连接是否仍然“已连接”/有效:
public class TaskActionStatus : Hub
{
public void SendMessage()
{
if (HubConnectionManager.IsOnline(Context.ConnectionId))
{
this.Clients.Client(Context.ConnectionId).actionInit("test");
}
}
...
}