使用 MVC4 向特定客户端发送 SignalR 推送通知

SignalR push-notification to specific client with MVC4

我正在尝试将 SignalR 与 MVC4 c# 项目一起使用,以便仅向选定的客户端发送推送通知。 为此,我通过将 'Context.ConnectionId' 存储在 c# 静态变量中来使用 'context.Clients.Client' {因为无法将会话与 signalr 一起使用}。 但是由于 'contextConnectionId' 是一个静态变量;该消息仍然广播给所有客户:(

除了信号会话或任何其他优雅的方式之外,还有其他选择吗? (发现很少相关 post 但没有具体答案)

代码如下:

javaScript

 $(document).ready(function (){
 {
    var chat = $.connection.PushNotify;
    chat.client.addNewMessageToPage = function (type, message) {
        if(type == "something")
        {
            alert(message);
        }
    }
    // Start the connection.
    $.connection.hub.start().done(function () {
        chat.server.send($('').val(), $('').val());
    });
 )}

在 c# HUB 中

[HubName("PushNotify")]
public class PushNotify : Hub
{
    public void Send(string name, string message)
    {
        //assume its c# static variable
        GlobalVariable.contextConnectionId = Context.ConnectionId;
    }
}
public class PushNotification
{
    public void SendMessage(string message, string type = "msg")
    {
        if (!string.IsNullOrEmpty(GlobalVariable.contextConnectionId))
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<PushNotify>();
            context.Clients.Client(GlobalVariable.contextConnectionId).addNewMessageToPage(type, message);
        }

    }
}

我认为您的示例不会按预期工作。当您将连接映射到静态变量时,您实际上将静态变量覆盖到调用 Send 方法的最后一个连接。

Each client connecting to a hub passes a unique connection id. You can retrieve this value in the Context.ConnectionId property of the hub context.

这意味着您的 GlobalVariable.contextConnectionId 不能是简单的字符串。您必须以某种方式映射您的客户,并且每个客户都将有一个唯一的连接 ID。也许在这里一本字典就足够了,或者拥有包含更多信息的class。 (即浏览器信息、IP 地址...)

(引自link)这应该对你有帮助:http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections

编辑

提供更多信息:

我认为解决您问题的最简单方法是使用群组。 http://www.asp.net/signalr/overview/guide-to-the-api/working-with-groups

您的中心 class 将包含加入群组的方法:

public Task JoinGroup(string groupName)
{
    return Groups.Add(Context.ConnectionId, groupName);
}

public Task LeaveGroup(string groupName)
{
    return Groups.Remove(Context.ConnectionId, groupName);
}

假设一个 PostMessage to group 只发送给给定的组:

public void SendMessage(string groupName, string message, string type = "msg")
{
    var context = GlobalHost.ConnectionManager.GetHubContext<PushNotify>();
    context.Clients.Group(groupName).addNewMessageToPage(type, message);
}

当您的客户加入时,他们可以连接到一个组,其他一切都将由 SignalR 处理。

从客户端加入群组并发布消息:

var chat = $.connection.PushNotify;
$.connection.hub.start().done(function () {
    chat.server.joinGroup("Group1");
    chat.server.sendMessage("Group1", "Hi There");
});

接收消息也是如此

chat.client.addNewMessageToPage = function (type, message) {
   ...
}

其他解决方案

另一种解决方案可能是使用您自己的映射或 SignalR 连接映射。这些解决方案需要覆盖 OnConnected 和 OnDisconnected 方法并映射您的连接。即:

private readonly static ConnectionMapping<string> _connections = 
        new ConnectionMapping<string>();

public override Task OnConnected()
{
    string name = Context.User.Identity.Name;
    _connections.Add(name, Context.ConnectionId);
    return base.OnConnected();
}

public override Task OnDisconnected(bool stopCalled)
{
    string name = Context.User.Identity.Name;
    _connections.Remove(name, Context.ConnectionId);
    return base.OnDisconnected(stopCalled);
}

public void SendChatMessage(string who, string message)
{
    string name = Context.User.Identity.Name;
    foreach (var connectionId in _connections.GetConnections(who))
    {
        Clients.Client(connectionId).addChatMessage(name + ": " + message);
    }
}

就像这个例子:http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#inmemory