代码之家  ›  专栏  ›  技术社区  ›  JacobIRR

尝试轮询现有连接时未触发信号发送方法

  •  0
  • JacobIRR  · 技术社区  · 7 年前

    我将最新版本的signar与jQuery结合使用,得到了一些奇怪的行为,用户断开了连接,但仍然挂在我的“UserQueue”中,尽管断开了连接。

    我认为这可能与页面刷新似乎会触发 OnDisconnected OnConnected 事件几乎同时发生。当我在其中一个方法中设置断点并单步执行时,我的指针在每一步的两个方法之间来回跳动( F10 ).

    我想和每个人核对一下 未连接 事件以找出谁实际连接到我的应用程序。我想在OnConnected事件中从我的C#代码中触发一个JS事件,然后允许客户端/前端发回用户存在的确认:

    public override Task OnConnected()
    {
        // Check for other users:
        Clients.All.checkForOtherUsers();
    
        // Do stuff with my user queue
        var curmodelId = GetModelId(Context);
        var curUserConnection = GetCurrentUser(Context);
        // First create the ledger is missing, setting the modelId as the first key
        if (_ledger == null)
        {
            _ledger = new ConnectionLedger(curmodelId, curUserConnection);
        }
        else
        {
            // key not found, create new connection pool this model
            if (!_ledger.PoolIds.Contains(curmodelId))
            {
                _ledger.AddConnectionPool(curmodelId, curUserConnection);
            }
            else
            {
                var curModelPool = _ledger.ConnectionPools.First(x => x.Id == curmodelId);
                curModelPool.UserQueue.Enqueue(curUserConnection);
            }
        }
    
        return base.OnConnected();
    }   
    

    现在在客户端JS中,如果我有以下代码:

    modelHub.client.checkForOtherUsers = function () {
        // I can see logging here if I add console.log("checking for other users...")
        modelHub.server.send();
    }
    

    ...我在等我的C# Send 方法接收回上下文(如果用户实际在客户端等待JS执行)并更新我的 UserQueue :

    public void Send()
    {
        var curmodelId = GetModelId(Context);
        var curModelPool = _ledger.ConnectionPools.First(x => x.Id == curmodelId);
        var curUserConnection = GetCurrentUser(Context);
        curModelPool.UserQueue.Enqueue(curUserConnection);
    }
    

    ... 但是我的 邮寄 方法永远不会被激发,即使我直接从JS控制台激发它 $.connection.modelingHub.server.send() .

    为什么Send方法没有启动?信号器库的事件顺序/异步性质是否导致了这种情况?

    对总体设计的评论也很受欢迎(因为我怀疑这可能很愚蠢),但请注意,我无法访问 Context.User Clients.User 因为我的自定义身份验证配置。

    1 回复  |  直到 7 年前
        1
  •  1
  •   idubnori    7 年前

    似乎有以下两个原因。

    服务器端
    打电话不好 Clients.All.checkForOtherUsers(); 在内部 OnConnected() .
    我建议连接后再打电话。

    请参阅 SignalR - Send message OnConnected

    客户端
    可能需要注册 modelHub.client.checkForOtherUsers = function () { 在调用start方法之前。

    通常在调用start方法之前注册事件处理程序 建立连接。如果要注册某个事件 在建立连接之后,您可以这样做,但是 在调用之前,必须注册至少一个事件处理程序 启动方法。
    - How to establish a connection