【发布时间】:2014-03-31 16:02:21
【问题描述】:
我的连接没有启动。 此代码在 1.x 中有效,但在版本 2 中无效。
SignalR 似乎正在尝试连接但没有成功。 永远不会调用 hub 方法。
附加发送带有 SignalR 调试的图像。
Javascript:
<script type="text/javascript">
$.connection.hub.logging = true;
var options = { transport: ['webSockets', 'longPolling'] };
$(function() {
var userHub = $.connection.userHub;
//Iniciar connecção
window.hubReady = $.connection.hub.start(options);
window.hubReady.done(function () {
userHub.server.ini();
});
userHub.client.iniDone = function (connectionId) {
console.log(connectionId);
};
$.connection.hub.connectionSlow(function() {
console.log('slow connection...');
});
window.hubReady.fail(function(error) {
console.log(error);
});
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 2000);
});
});
</script>
中心:
[HubName("userHub")]
public class UserHub : Hub
{
public void Ini()
{
Clients.Client(Context.ConnectionId).iniDone(string.Format("Conectado com o id: {0}", Context.ConnectionId));
}
public override Task OnConnected()
{
var connectionId = Context.ConnectionId;
var email = string.IsNullOrWhiteSpace(Context.User.Identity.Name) ? Context.Headers["email"] : Context.User.Identity.Name;
if (email != null && connectionId != null)
UserData.GetInstance(email).ConnectionsIds.Add(connectionId);
return base.OnConnected();
}
public override Task OnDisconnected()
{
var connectionId = Context.ConnectionId;
var email = string.IsNullOrWhiteSpace(Context.User.Identity.Name) ? Context.Headers["email"] : Context.User.Identity.Name;
if (email != null && connectionId != null)
UserData.GetInstance(email).ConnectionsIds.Remove(connectionId);
return base.OnDisconnected();
}
}
调试:
编辑:
我发现了问题!我的 Singleton 的 GetInstance 方法有问题。
public static UserData GetInstance(string username)
{
if (_sharedUsers == null)
lock (_lockCreate)
_sharedUsers = new Dictionary<string, UserData>();
if (!_sharedUsers.ContainsKey(username))
lock (_lockAdd)
_sharedUsers.Add(username, new UserData(username));
return _sharedUsers[username];
}
方法总是在这里停止:lock (_lockAdd)
我想保存所有用户connectionsIds有什么想法吗?
谢谢
【问题讨论】:
-
所以在服务器上的集线器中,您没有看到
OnConnected被调用?还是只是Ini没有被调用? -
您列出的调试图像还显示所有连接服务器的尝试都超时。你能确认
http://localhost:38219的服务器正在运行吗? -
OnConnected 和 OnDisconnected 被调用。 Ini() 没有被调用
-
是的,它在 IIS Express 上运行
-
那么在调试服务器的时候,你能看到
OnConnected成功完成了吗?只是试图排除任何服务器错误。
标签: c# javascript asp.net-mvc signalr