C# – SignalR send message to single connectionId

asp.netcsignalrsignalr-hub

I have an asp.net classic website. ive got SignalR basic functionality to work (where one client send messages to rest of the clients). but now i want to send Messages only to specific connectionsIDs.

my Hub :

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

        <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();
                });


            });

Problem is i dont really know how to send to one specific ConnectionID with hub, since Clients.updateMessages(messages); send messages to all of them. how do i solve this?

P.S: ive already looked at: Send server message to connected clients with Signalr/PersistentConnection

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

that didnt worked.

Best Answer

Well, you can send a message to a single client from a Hub like so:

Clients.Client(someConnectionIdIWantToSendToSpecifically).doSomething();

The trick is you need to know the connection ID you want to send the message to. Even more specifically you probably want to know the logical identity of the thing you want to send the message too since that logical identity could have multiple connections or have dropped and reconnected under a completely different connection id. Mapping of connections to logical identities is something SignalR leaves up to the application itself.

Related Topic