我正在使用Signalr javascript客户端连接到sugnalr集线器。
Hub OnConnected方法是这个
public override Task OnConnected()
{
try
{
var cType = Context.QueryString["type"];
var connectionId = Context.ConnectionId;
var connectedUserList = (from d in Users
where d.ClientType == cType
select d).ToList();
if (connectedUserList.Count > 0)
{
var conUser = connectedUserList.First<ConnectedUsers>();
conUser.ConnectionIds.Add(connectionId);
}
else
{
var newUser = new ConnectedUsers
{
ConnectionIds = new HashSet<string> {connectionId}
,
ClientType = cType
};
Users.Add(newUser);
}
}
catch (Exception ex)
{
}
return base.OnConnected();
}
其他Hub方法
public void PushMessage()
{
try
{
var context = GlobalHost.ConnectionManager.GetHubContext<MainHub>();
var user = (from d in Users
where d.ClientType == "WIN"
select d).Single();
context.Clients.Clients(user.ConnectionIds.ToArray()).sendAlert("EXCEL");
}
catch (Exception e)
{
//throw;
}
}
和Javascript客户端连接代码如下
<html>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="@Url.Content("http://localhost:1010/signalr/hubs")"></script>
@RenderSection("scripts", required: false)
</body>
</html>
<script type="text/javascript">
var currentHub = [];
var connectionDetails = {};
var SignalRHandler = {
_settings: {
connectionDetails: {
id: "1",
userName: ""
},
hub: $(),
callBack: $(),
url: ""
},
initilaize: function(options) {
this._settings = $.extend(true, this._settings, options);
if (!$.connection)
alert("$.connection undefined");
else
this._bindEvents();
},
_bindEvents: function() {
// Start Hub
$.connection.hub.url = this._settings.url;
$.connection.hub.qs = { 'type': 'WEB' }
currentHub = $.connection[this._settings.hub], connectionDetails = this._settings.connectionDetails;
if (currentHub != undefined) {
currentHub.client.sendAlert = this._settings.callBack;
$.connection.hub.start().done(function() {
currentHub.server.OnConnected();
});
$.connection.hub.disconnected(function() {
setTimeout(function() {
$.connection.hub.start().done(function() {
currentHub.server.OnConnected();
});
}, 2000); // Restart connection after 2 seconds.
});
}
},
pushChatMessage: function () {
currentHub.server.pushMessage();
},
showMsg:function(msg) {
alert(msg);
}
};
jQuery(document).ready(function($) {
SignalRHandler.initilaize({
callBack: SignalRHandler.showMsg,
hub: "mainHub",
url: "http://localhost:1010/signalr/"
});
});
</script>
该代码运行良好,可以连接到集线器并连续接收来自集线器的消息。
但是,当我检查调试器控制台时,它说。
未被捕获的TypeError:currentHub.server.OnConnected不是函数(…)
如何摆脱这个错误?
最佳答案
从SignalR客户端调用服务器方法时,方法名称应为驼峰式,除非您在集线器中的方法上使用HubMethodName
属性指定了其他名称。
因此,在您的情况下,调用OnConnected
方法应如下所示:currentHub.server.onConnected();
参考:https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#callserver