查询仅向某些用户广播的连接

时间:2013-07-30 15:34:29

标签: asp.net signalr

在我的页面中,我正在建立我的连接:

var connection = $.connection("/notification-connection");
connection.received(function (data) {
    //whatever
});
connection.start({ items: [{ "ValidationTicket": ticket}] });

在后端,我如何向ticket.ClientCode = XYZ的用户广播通知?我知道我可以将用户分组,但我也希望根据多个条件向用户广播,例如ticket.ClientCode = XYZ和ticket.UserName = JohnDoe,在这种情况下,组不会真正起作用。

2 个答案:

答案 0 :(得分:0)

如果有人在寻找类似的解决方案,我最终会得到类似的结果:

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

答案 1 :(得分:0)

上面的代码示例是管理用户和组的好方法,但如果您希望组列表在服务器重新启动或应用程序池回收期间存活,则无法将组信息存储在内存中 - 您需要坚持使用文件或数据库。