2012-04-02 55 views
1

目前我已经学会了如何从服务器端通知集线器。集线器然后将通知广播给客户端。hubcontext为空信号器

我正在处理的上下文基于发送好友请求(类似于facebook)。 如果X先生向Y女士发出请求,那么只有Y女士才会弹出通知。

因此,我决定与团队合作。我在想一个组 - 一个用户。

的问题是,我想,在轮毂开始我会做:

$ .connection.hub.start(函数(){hub.login(XXX);});

其中XXX将是会话的用户名或用户ID。我不知道该怎么做。

然后,我尝试使用用户名或用户ID制作一个隐藏标签,将其填充到page_load上,然后从客户端获取。但客户端在服务器端工作。

然后我尝试使用集线器上下文的连接ID。但问题似乎是,几乎所有的内容和组织管理器都是空的。是因为我正在使用集线器的一个实例吗?或者因为我有静态方法? (我需要具有静态/或者有一个实例,因为我打电话从其他的服务器端代码这些方法)

 using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using SignalR.Hubs; 
using SignalR; 
using SignalR.Hosting.AspNet; 
using System.Web; 
using System.Web.SessionState; 

namespace DataLayer 
{ 
    public class NotificationHub: Hub 
    { 
     private static NotificationHub instance; 

     private NotificationHub() { } 

     public static NotificationHub Instance 
     { 
      get 
      { 
       if (instance == null) 
        instance = new NotificationHub(); 
       return instance; 
      } 
     } 

     public void NotifyClients(int gid, string value) 
     { 
      IConnectionManager connectionManager = (IConnectionManager)AspNetHost.DependencyResolver.GetService(typeof(IConnectionManager)); 
      dynamic clients = connectionManager.GetClients<NotificationHub>(); 
      clients[gid.ToString()].newNotification(value); 
      //let us then try to use connection id, but this.Context.ConnectionId is null 

     } 

     public void Login(string gid) 
     { 
      AddToGroup(gid); 
     } 

    } 
} 

可能有一些其他的解决方法,我想做些什么呢? (即让每个人都有自己的通知?)

+0

这个问题有什么问题吗? – test 2012-04-02 16:59:15

+0

你并没有提出任何问题或任何情况。 – 2012-04-02 17:12:35

+0

@DrewMarsh你认为现在好吗? – test 2012-04-02 17:37:21

回答

4

您对js的引用应该是$.connection.notificationHub而不是$.connection.hub。它来自您的集线器的类名。如果你喜欢,你可以用[HubName(“name”)]属性重命名它。

此外,SignalR将管理您的集线器的生命周期。您不需要创建实例。我会仔细检查来源,看看它的每个电话或单身等。

关于(如果我正确阅读)以任何方式使用朋友的连接ID - 这不是一个好主意。目前,它们没有安全保障,并且可以让用户很容易地伪装成任何其他用户。

编辑:另一个提示 - 在集线器内,您不必使用ConnectionManager获取客户端。你可以使用客户属性。 IE,clients [gid.ToString()]。newNotification(value);

+1

就是这样。我应该nevered实例化一个枢纽。你只能称它。然后,我设法从会话中获取userId并将其传递到集线器中的登录方法,在那里为会话中的用户标识创建一个组。也正因为如此,如果我决定在IE和Chrome上打开相同的网站,我会有不同的connectionID,但在这种情况下,我会使用相同的组:),这很好。如果有人遇到问题,请联系我获取基本解决方案。谢谢,我的朋友 – test 2012-04-02 22:38:14