【问题标题】:SignalR send message to single connectionIdSignalR 向单个 connectionId 发送消息
【发布时间】:2012-11-13 02:48:16
【问题描述】:

我有一个 asp.net 经典网站。我让 SignalR 基本功能正常工作(一个客户端向其余客户端发送消息)。但现在我只想将消息发送到特定的连接 ID。

我的集线器:

**    [HubName("chatHub")]
    public class ChatHub : Hub 
    {
        public static List<string> messages = new List<string>();

        public void GetServiceState()
        {
            Clients.updateMessages(messages);
        }

        public void UpdateServiceState()
        {
            messages.Add(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));

            Clients.updateMessages(messages);
        }

    }**

ASP 代码:

        <script type="text/javascript">
            $(function () {
                // creates a proxy to the health check hub

                var healthCheckHub = $.connection.chatHub;
                console.log($.connection.hub)
                // handles the callback sent from the server
                healthCheckHub.updateMessages = function (data) {
                    $("li").remove();

                    $.each(data, function () {
                        $('#messages').append('<li>' + this + '</li>');
                        console.log($.connection);
                    });
                };

                $("#trigger").click(function () {
                    healthCheckHub.updateServiceState();
                });

                // Start the connection and request current state
                $.connection.hub.start(function () {
                    healthCheckHub.getServiceState();
                });


            });

问题是我真的不知道如何使用集线器发送到一个特定的 ConnectionID,因为 Clients.updateMessages(messages);向他们所有人发送消息。我该如何解决这个问题?

P.S:我已经看过了:Send server message to connected clients with Signalr/PersistentConnection

http://riba-escapades.blogspot.dk/2012/05/signalr-send-messages-to-single-client.html

那没用。

【问题讨论】:

    标签: c# asp.net signalr signalr-hub


    【解决方案1】:

    好吧,您可以像这样从 Hub 向单个客户端发送消息:

    Clients.Client(someConnectionIdIWantToSendToSpecifically).doSomething();
    

    诀窍是您需要知道要将消息发送到的连接 ID。更具体地说,您可能还想知道要发送消息的事物的逻辑标识,因为该逻辑标识可能有多个连接,或者在完全不同的连接 ID 下断开并重新连接。将连接映射到逻辑标识是 SignalR 留给应用程序本身处理的事情。

    【讨论】:

    • 我这样做是为了在用户登录后,connectionID 将始终与 userID 相同。在我的应用程序中,我这样做是为了在用户按下发送按钮后,我找出谁是我的追随者,并仅向这些连接 ID 发送消息。我不知道这是否是明智之举。任何想法如何以更智能的方式实现它?
    • 我见过的大多数实现都使用逻辑用户身份到活动连接 ID 的一对多关系映射。
    • 最后一个问题,如果我向离线的connectionID发送消息会发生什么?
    • 我真的不记得了,也没有时间检查这一秒,但相当确定这对你来说只是一个无操作。要检查,请尝试 Client("abc123").foo() 之类的东西,看看会发生什么。
    • @Mr_Green 要将消息发送到当前客户端,您只需执行以下操作:Clients.Caller.doSomething();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多