2

我想也许我不完全理解在 SignalR 中实现组的正确方法:)

我正在使用 SignalR 集线器和一些 JS。相关代码如下:

public class NotificationHub : Hub
{

    public void RegisterUser()
    {
        if (Context.User.Identity.IsAuthenticated)
        {

            var username = Context.User.Identity.Name;
            Groups.Add(Context.ConnectionId, username);

            //check roles
            var roles = Roles.GetRolesForUser(username);
            foreach (var role in roles)
            {
                Groups.Add(Context.ConnectionId, role);
            }
        }
    }

    public override Task OnConnected()
    {
        RegisterUser();
        return base.OnConnected();
    }

    //rejoin groups if client disconnects and then reconnects
    public override Task OnReconnected()
    {
        RegisterUser();
        return base.OnReconnected();
    }

}

单步执行此代码表明它按预期工作。

然而,当我真正来发送消息时,广播到所有作品。如果我尝试通过他们的用户名(他们自己的特定组)向特定用户广播,则不会发生任何事情。

public void BroadcastNotification(List<string> usernames, Notification n)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        foreach (var username in usernames)
        {
            context.Clients.Group(username).broadcastMessage(new NotificationPayload()
            {
                Title = n.Title,
                Count = UnitOfWork.NotificationRepository.GetCount(),
                Notification = n.Body,
                Html = RenderPartialViewToString("_singleNotification", n)
            });
        }

    }

看起来小组不像我想象的那样工作。我在这里缺少一个步骤吗?

4

1 回答 1

0

我没有看到您的客户端代码,但我认为您必须明确启动集线器,并在收到“通知”之前“加入”“组”。所以在你的客户代码中,像

$.connection.hub.start()
 .done(function() {
              chat.server.join();
 });

在您的集线器中,“加入”方法类似于您已有的方法:

public Task Join()
{
    if (Context.User.Identity.IsAuthenticated)
    {
        var username = Context.User.Identity.Name;
        return Groups.Add(Context.ConnectionId, username);
    } 
    else
    {
        // a do nothing task???? 
        return Task.Factory.StartNew(() =>
        {
            // blah blah 
        });
    }   
}
于 2013-05-16T21:41:50.327 回答