【发布时间】:2020-09-23 19:00:12
【问题描述】:
我有我的 SignalR 服务,并尝试将它与一个简单的 .Net Core 应用程序连接起来。当浏览器调用https://imubitsignalr.service.signalr.net:5001/client/negotiate?hub=usercount
我收到 ERR_CONNECTION_TIMED_OUT 的错误。
我错过了什么?
程序:index.cshtml
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
function bindConnectionMessage(connection) {
var messageCallback = function (message) {
console.log('message' + message);
if (!message) return;
var userCountSpan = document.getElementById('users');
userCountSpan.innerText = message;
};
connection.on("updateCount", messageCallback);
connection.onclose(onConnectionError);
}
function onConnected(connection) {
console.log('connection started');
}
function onConnectionError(error) {
if (error && error.message) {
console.error(error.message);
}
}
var connection = new signalR.HubConnectionBuilder().withUrl('/chat').build();
bindConnectionMessage(connection);
connection.start()
.then(function () {
onConnected(connection);
})
.catch(function (error) {
console.error(error.message);
});
});
</script>
在 startup.cs 我设置:
services.AddSignalR(hubOptions => {
hubOptions.EnableDetailedErrors = true;
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(3);
}).AddAzureSignalR();
集线器代码:
public class UserCount : Hub
{
private static int Count;
public override Task OnConnectedAsync()
{
Count++;
base.OnConnectedAsync();
this.Clients.All.SendAsync("updateCount", Count);
return Task.CompletedTask;
}
public override Task OnDisconnectedAsync(Exception exception)
{
Count--;
base.OnDisconnectedAsync(exception);
this.Clients.All.SendAsync("updateCount", Count);
return Task.CompletedTask;
}
}
映射中心:
app.UseAzureSignalR(routes =>
{
routes.MapHub<UserCount>("/chat");
});
【问题讨论】:
-
请在后端添加您的集线器配置代码。我还注意到您正在尝试连接到
hub=usercount,但在客户端代码中您有withUrl('/chat'),因此后端集线器配置代码示例很重要。 -
@Kiril1512 谢谢!我添加了它。设置超时后我的错误`失败:WebSocket握手期间出错:意外响应代码:404`
-
添加您在启动时使用的代码来映射集线器。
-
@Kiril1512 现在,谢谢!
-
@Kiril1512 你现在看到问题了吗?