1

在我的页面中,我正在像这样设置我的连接:

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

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

4

2 回答 2

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());
}
于 2013-07-30T16:27:50.077 回答
0

上面的代码示例是管理用户和组的好方法,但是如果您希望您的组列表在服务器重新启动或应用程序池回收后仍然存在,您不能将组信息存储在内存中 - 您需要持久保存到文件中或数据库。

于 2013-08-12T21:28:53.110 回答