获得听众的数量,客户连接到集线器SignalR [英] Get number of listeners, clients connected to SignalR hub

查看:221
本文介绍了获得听众的数量,客户连接到集线器SignalR的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法找出(客户机连接到集线器?)

Is there a way to find out the number of listeners (clients connected to a hub?)

我试图运行/启动如果至少有一个客户端连接任务,否则不启动:

I'm trying to run/start a task if at least one client is connected, otherwise do not start it:

[HubName("taskActionStatus")]
public class TaskActionStatus : Hub, IDisconnect
{
    static CancellationTokenSource tokenSource;

    public void GetTasksStatus(int? siteId)
    {
        tokenSource = new CancellationTokenSource();
        CancellationToken ct = tokenSource.Token;

        ITaskRepository taskRepository = UnityContainerSetup.Container.Resolve<ITaskRepository>();

        // init task for checking task statuses
        var tasksItem = new DownloadTaskItem();
        taskRepository.GetTasksStatusAsync(siteId, tasksItem, ct);

        // subscribe to event [ listener ]
        tasksItem.Changed += new EventHandler<TaskEventArgs>(UpdateTasksStatus);
    }

    public void UpdateTasksStatus(object sender, TaskEventArgs e)
    {
        Clients.updateMessages(e.Tasks);
    }

    // when browsing away from page
    public Task Disconnect()
    {
        try
        {
            tokenSource.Cancel();
        }
        catch (Exception)
        {
            //
        }

        return null;
    }
}

感谢

推荐答案

有没有办法得到SignalR这样算不算这样。你必须使用集线器的的onConnect() OnDisconnect()的方法来保持自己算。

There is no way to get this count from SignalR as such. You have to use the OnConnect() and OnDisconnect() methods on the Hub to keep the count yourself.

与静态类简单的例子来保存计数:

Simple example with a static class to hold the count:

public static class UserHandler
{
    public static HashSet<string> ConnectedIds = new HashSet<string>();
}

public class MyHub : Hub
{
    public override Task OnConnected()
    {
        UserHandler.ConnectedIds.Add(Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        UserHandler.ConnectedIds.Remove(Context.ConnectionId);
        return base.OnDisconnected();
    }
}

您再拿到从计数 UserHandler.ConnectedIds.Count

这篇关于获得听众的数量,客户连接到集线器SignalR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆