以防万一有人四处寻找类似的解决方案,我最终会得到这样的结果:
public class NotificationConnection : PersistentConnection
{
public NotificationConnection()
{
if (Clients == null)
Clients = new ConcurrentDictionary<string, IRequest>();
}
public static ConcurrentDictionary<string, IRequest> Clients { get; private set; }
protected override Task OnConnected(IRequest request, string connectionId)
{
Clients.TryAdd(connectionId, request);
return base.OnConnected(request, connectionId);
}
protected override Task OnDisconnected(IRequest request, string connectionId)
{
IRequest outRequest;
Clients.TryRemove(connectionId, out outRequest);
return base.OnDisconnected(request, connectionId);
}
}
然后我可以像这样广播到我想要的连接:
public void SendNotification(Notification notification)
{
if(notification == null)
throw new ArgumentNullException("notification");
//...
var excludedConnectionIds = NotificationConnection.Clients.Where(x => x.Value.Items.Values.Cast<ValidationTicket>().Any(y => y == null || y.UserKeyNames == null || y.ClientCode != notification.ClientCode || !y.UserKeyNames.Contains(notification.UserKeyName))).Select(x => x.Key);
var context = GlobalHost.ConnectionManager.GetConnectionContext<NotificationConnection>();
context.Connection.Broadcast(data, excludedConnectionIds.ToArray());
}