代码之家  ›  专栏  ›  技术社区  ›  Trevor Daniel

信号器获取连接ID

  •  1
  • Trevor Daniel  · 技术社区  · 6 年前

    我第一次尝试使用signaler将长时间运行的进程的进度反馈给用户

    我发现了一些.NET核心示例,但最接近的似乎是使用旧版本的Signaler。

    我正在努力得到“连接ID”。我读了很多这样的问题和答案,但似乎仍然无法得到正确的价值。

    这是我从演示项目中找到的代码:

    // Helper functions added for test purposes
    function openConnection() {
        progressConnection = new signalR.HubConnectionBuilder().withUrl("/progressDemo").build();
        debugger;
        progressConnection
            .start()
            .then(() => {
                progressConnectionId = progressConnection.connection.connectionId;
                $("#connId").html(progressConnectionId);
                $("#startButton").removeAttr("disabled");
                $("#dropConnectionButton").removeAttr("disabled");
                $("#openConnectionButton").attr("disabled", "disabled");
                $("#msg").html("Connection established");
                console.log("Connection Id: " + progressConnectionId);
            })
            .catch(() => {
                $("#msg").html("Error while establishing connection");
            });
    }
    

    错误是“connectionid”在行上未定义:

    progressConnectionId = progressConnection.connection.connectionId;
    

    任何帮助都将不胜感激!

    1 回复  |  直到 6 年前
        1
  •  0
  •   Trevor Daniel    6 年前

    好啊。。。很明显现在我已经解决了:)

    我的中心现在看起来是这样的:

    public override Task OnConnectedAsync()
    {
        //Count++;
        Interlocked.Increment(ref Count);
    
        base.OnConnectedAsync();
        Clients.All.SendAsync("updateCount", Count);
        Clients.All.SendAsync("connected", Context.ConnectionId);
        return Task.CompletedTask;
    }
    

    重要的一行是发送回连接id的那一行

    Clients.All.SendAsync("connected", Context.ConnectionId);
    

    在客户端,我监听“connected”并设置connectionid变量:

    progressConnection.on("connected", (connectionId) => {
        progressConnectionId = connectionId;
        $("#connId").html(progressConnectionId);
        $("#startButton").removeAttr("disabled");
        $("#dropConnectionButton").removeAttr("disabled");
        $("#openConnectionButton").attr("disabled", "disabled");
        $("#msg").html("Connection established");
        console.log("Connection Id: " + progressConnectionId);
    });