返回SignalR中已连接客户端的计数。不解雇客户端功能

时间:2014-02-14 20:19:05

标签: signalr

我正在尝试使用SignalR将所有连接的计数返回给Web客户端。我通过在集线器OnConnected()方法上触发逻辑来增加并保持客户端计数。

public class PopHub : Hub
{
    public static List<string> Users = new List<string>(); 

    public override Task OnConnected()
    {
        var clientId = GetClientId();

        if (Users.IndexOf(clientId) == -1)
        {
            Users.Add(clientId);
        }

        Send(Users.Count);

        return base.OnConnected();
    }

    public void Send(int count)
    {
        Clients.All.updateUsersOnlineCount(count);   
    }

使用外部控制台客户端(触发OnConnected())逐步执行我的代码,表明我正在遍历Send(int count),计数为1.

在我的网络客户端上,我将JS配置为

$(function() {
    var hub = $.connection.popHub;

    hub.client.updateUsersOnlineCount = function(count) {
        console.log(count);
    };

    $.connection.hub.start().done(function() {
        console.log('connected');
    });
}());

最后是我生成的js的片段

proxies.popHub = this.createHubProxy('popHub'); 
    proxies.popHub.client = { };
    proxies.popHub.server = {
        popClient: function (message) {
            return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["PopClient"], $.makeArray(arguments)));
         },

        query: function () {
            return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["Query"], $.makeArray(arguments)));
         },

        send: function (count) {
            return proxies.popHub.invoke.apply(proxies.popHub, $.merge(["Send"], $.makeArray(arguments)));
         }
    };

**请注意,PopclientQuery是不相关的服务器端事件,其中有一些工作可以让我进行一些健全性检查。知道为什么我的客户updateUsersOnlineCount功能没有像我期望的那样记录连接数吗?

1 个答案:

答案 0 :(得分:0)

请不要在OnConnected中进行,请尝试一下,可能是Base.OnConnected尚未执行,因此尚未准备好向客户端广播。

//Client
$.connection.hub.start().done(function() {
        console.log('connected');
        hub.server.ClientCount();
    });

 //Hub
 public static List<string> Users = new List<string>(); 

 public override Task OnConnected()
 {
    var clientId = GetClientId();

    if (Users.IndexOf(clientId) == -1)
    {
        Users.Add(clientId);
    }

    //Send(Users.Count); //not calling this since it's not working

    return base.OnConnected();
 }
 public void ClientCount()
    {
        Clients.All.updateUsersOnlineCount(Users.Count);   
    }