SignalR向单个connectionId发送消息

时间:2012-11-12 17:41:27

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

我有一个asp.net经典网站。我已经有了SignalR基本功能(一个客户端向其他客户端发送消息)。但现在我只想将消息发送到特定的connectionID。

我的中心:

**    [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

没有用。

1 个答案:

答案 0 :(得分:25)

好吧,您可以从集线器向单个客户端发送消息,如下所示:

Clients.Client(someConnectionIdIWantToSendToSpecifically).doSomething();

技巧是您需要知道要将消息发送到的连接ID。更具体地说,您可能想知道您要发送消息的事物的逻辑身份,因为该逻辑身份可能具有多个连接,或者已经在完全不同的连接ID下丢弃和重新连接。将连接映射到逻辑身份是SignalR留给应用程序本身的东西。

相关问题