SignalR send message to single connectionId

我是研究僧i 提交于 2020-05-10 07:25:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13348654/signalr-send-message-to-single-connectionid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!