我使用signalR。组功能无法正常工作。
这是我的中心:
public class BasketHub : Hub
{
public void Login(int companyId)
{
string groupName = "company" + companyId;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<BasketHub>();
context.Groups.Add(Context.ConnectionId, groupName);
}
public void Logout(int companyId)
{
string groupName = "company" + companyId;
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<BasketHub>();
context.Groups.Remove(Context.ConnectionId, groupName);
}
}
这是使用服务器端:
public void OrderConfirm(OrderConfirmModel orderConfirmModel)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<BasketHub>();
var groupName = "company" + orderConfirmModel.CompanyId;
context.Clients.Group(groupName).orderConfirm(orderConfirmModel.DidNewOrder);
context.Clients.Group(groupName).newOrderCount(orderConfirmModel.DidNewOrder);
context.Clients.Group(groupName).didGetNotification(orderConfirmModel.BasketId);
}
这是客户:
$(function () {
var basketHub = $.connection.basketHub;
basketHub.client.newOrderCount = function (isNewOrder) {
// some code
}
basketHub.client.didGetNotification = function (basketId) {
// some code
}
basketHub.client.orderConfirm = function (isNewOrder) {
// some code
}
$.connection.hub.start();
});
此处是群组添加和删除客户端:
$(function () {
var basketHub = $.connection.basketHub;
$.connection.hub.start().done(function () {
basketHub.server.login($scope.Company.Id);
$('#logoutBtn').click(function () {
basketHub.server.logout($scope.Company.Id);
});
});
$(window).bind('beforeunload', function (e) {
basketHub.server.logout($scope.Company.Id);
});
});
我在BasketHub的上下文中创建了该组。但是,当我尝试使用该组时,我不会达到它。并且客户端没有触发通知。
我可以像下面这样使用它:
context.Clients.All.orderConfirm(orderConfirmModel.DidNewOrder);
context.Clients.All.newOrderCount(orderConfirmModel.DidNewOrder);
context.Clients.All.didGetNotification(orderConfirmModel.BasketId);
最诚挚的问候。
答案 0 :(得分:0)
我找到了解决方案。编写一个角度控制器,每个页面加载运行init(如layout-controller)。我在这里定义我的集线器并发出功能。 SingnalR小组工作正常。
$(function () {
var basketHub = $.connection.basketHub;
basketHub.client.orderConfirm = function (isNewOrder) {
$rootScope.$emit("basketOrderConfirm", isNewOrder);
}
basketHub.client.newOrderCount = function (isNewOrder) {
$rootScope.$emit("newOrderCount", isNewOrder);
}
basketHub.client.didGetNotification = function (basketId) {
$rootScope.$emit("didGetNotification", basketId);
}
$.connection.hub.start().done(function () {
basketHub.server.login($scope.Company.Id);
$('#logoutBtn').click(function () {
basketHub.server.logout($scope.Company.Id);
});
});
$(window).bind('beforeunload', function (e) {
basketHub.server.logout($scope.Company.Id);
});
});