2013-05-13 71 views
1

我想也許我不完全理解在SignalR中實現組的正確方法:)SignalR:組廣播不工作

我正在使用與一些JS耦合的SignalR集線器。 相關的代碼如下所示:

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

    } 

看來,這些團體不像我以前想象的那樣工作。有沒有我在這裏失蹤的一個步驟?

回答

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