我正在尝试使用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;
任何帮助将不胜感激!
答案 0 :(得分:1)
我想下面会更有效,因为它不会将连接ID发送到所有已连接的ID ...
public override Task OnConnectedAsync()
{
//Count++;
Interlocked.Increment(ref Count);
base.OnConnectedAsync();
Clients.All.SendAsync("updateCount", Count);
Clients.Client(Context.ConnectionId).SendAsync("connected", Context.ConnectionId);
return Task.CompletedTask;
}
答案 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);
然后在客户端上,我侦听“ 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);
});