有没有办法找出侦听器的数量(连接到集线器的客户端?)
如果连接了至少一个客户端,我试图运行/启动任务,否则不要启动它:
[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;
}
}
感谢
答案 0 :(得分:77)
无法从SignalR获得此数据。您必须使用Hub上的OnConnect()
和OnDisconnect()
方法自行保留计数。
使用静态类来保存计数的简单示例:
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
获取计数。
答案 1 :(得分:26)
对于版本2.1.1&lt;它应该是:
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(bool stopCalled)
{
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
答案 2 :(得分:2)
现在您需要:
public override Task OnConnectedAsync()
{
UserHandler.ConnectedIds.Add(Context.ConnectionId);
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnectedAsync(exception);
}
答案 3 :(得分:0)
在SIgnalR(版本2.4.1)中,这非常简单:
public int GetOnline()
{
return GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>().GetConnections().Count;
}
只需从客户端(:
答案 4 :(得分:0)
我想补充一点,如果您使用带有Azure功能和Azure SignalR服务的无服务器解决方案,则会解决以下问题:https://github.com/Azure/azure-functions-signalrservice-extension/issues/54
它是指此示例,您可以在其中使用事件网格来获取实时连接计数,这很不错。 https://github.com/aspnet/AzureSignalR-samples/tree/master/samples/EventGridIntegration