SignalR获取连接ID

问题描述 投票:1回答:1

我正在尝试使用SignalR向用户提供长时间运行过程的进度反馈

我找到了一些.Net Core示例,但最接近的似乎是使用旧版本的SignalR。

我正在努力获得“ConnectionId”。我已阅读了大量的SO问题和答案,但似乎仍无法获得正确的价值。

这是我发现的演示项目中的代码:

// 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;

任何帮助将不胜感激!

signalr
1个回答
0
投票

好的...这很明显现在我已经解决了:)

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

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);

在客户端,然后我监听“已连接”并设置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);
});
© www.soinside.com 2019 - 2024. All rights reserved.