SignalR将用户注册到集线器之外的组?

时间:2017-05-26 16:17:09

标签: c# asp.net-mvc-4 signalr

也许我只是没有正确理解SignalR中的组,但我对将用户注册到组部分感到困惑。我使用的是版本1.2.2。

此处:Groups演示了如何在较旧的SignalR中使用群组

我使用单例来维护集线器的上下文。我也在使用asp.net mvc 4.基本上,我想在更新期间对菜单项(使其闪存,添加新任务的数量等等)做一些事情,但仅限于分配任务的用户在那个选项中。

所以我想,服务器端在检查用户的角色时,我可以有条件地将它们分配给SignalR Group进行广播。

这是我的中心和单身人士课程:

public class TransactHub : Hub
{
    public Task RegisterForTransactionPartUpdates()
    {
        return Groups.Add(Context.ConnectionId, "Transact");
    }

    public void UpdateDailyTransactionTable(string r)
    {
        Clients.All.broadcastUpdate(r);
    }
}

和Singleton:

public class TransactSingleton
{
    private readonly static Lazy<TransactSingleton> _instance = new Lazy<TransactSingleton>(() => new TransactSingleton(GlobalHost.ConnectionManager.GetHubContext<TransactHub>().Clients));

    private TransactSingleton(IHubConnectionContext clients)
    {
        Clients = clients;
    }

    private IHubConnectionContext Clients
    {
        get;
        set;
    }

    public static Transact Instance
    {
        get
        {
            return _instance.Value;
        }
    }


    public void RegisterForTransactionUpdates()
    {
       //I want to register user here.. 
    }

    public void BroadcastUpdate(List<string> orders)
    {

    }  
}

那么我实际上会在哪里注册用户?此外,在使用以下新连接时:

        $.connection.hub.disconnected(function () {
            setTimeout(function () {
                $.connection.hub.start();
            }, 5000); // Restart connection after 5 seconds.
        });

用户是否会在群组中注册?

1 个答案:

答案 0 :(得分:0)

嗯,所以从这篇文章中可以看出:Hubs

public class ContosoChatHub : Hub
{
public override Task OnConnected()
{
    // Add your own code here.
    // For example: in a chat application, record the association between
    // the current connection ID and user name, and mark the user as online.
    // After the code in this method completes, the client is informed that
    // the connection is established; for example, in a JavaScript client,
    // the start().done callback is executed.
    return base.OnConnected();
}

public override Task OnDisconnected()
{
    // Add your own code here.
    // For example: in a chat application, mark the user as offline, 
    // delete the association between the current connection id and user name.
    return base.OnDisconnected();
}

public override Task OnReconnected()
{
    // Add your own code here.
    // For example: in a chat application, you might have marked the
    // user as offline after a period of inactivity; in that case 
    // mark the user as online again.
    return base.OnReconnected();
}
}

我应该使用OnConnected,并进行数据库调用以处理条件分配。我希望我能够在集线器之外处理数据库调用,但看起来不可能。如果我错了,请纠正我。