简体   繁体   中英

How can I send message to specific user with connectionId in SignalR

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. I've found some solution via stackoverflow but It didn't work on my codes. I have shared my c# code at below can you guys take a look at it please. my PROBLEM iS that I am able to trigger the hub method "Static_Send" but no way to trigger to the js trigger no response ! any solution please ...

Here is my hub class below;

public class ChatHub : Hub
{
        private static IHubContext hubContext =       GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
        public static string ConnectionID;

        public void Send( string message, string connectionid)
        {
            Clients.Client(connectionid).addNewMessageToPage(message, connectionid);
        }

        public void SendProxy(string name, string message, string connectionid, IHubContext hubContext)
        {

            hubContext.Clients.All.addNewMessageToPage(name, message, connectionid);
        }

        public override Task OnConnected()
        {
            ConnectionID = Context.ConnectionId.ToString();
            string username = Context.User.Identity.Name;
            return base.OnConnected();
        }
        public static void Static_Send(string message, string connectionid)
        {
            //hubContext.Clients.All.addNewMessageToPage(name, message, connectionid);
            hubContext.Clients.Client(connectionid).addNewMessageToPage(message, connectionid);
          //  hubContext.Clients.All.addNewMessageToPage(message, connectionid);
        }

    }

the below code is content my Mvc controller method

    public async System.Threading.Tasks.Task<ActionResult> Tetikle()
{    
var hubConnection = new HubConnection("http://localhost:57714");
                var hubProxy = hubConnection.CreateHubProxy("ChatHub");
                await hubConnection.Start();
                var connectionID = hubConnection.ConnectionId;
}

JS codes

    $(function () {
        var parent = window.parent.document.body;
        var chat = $.connection.chatHub;

       // $.connection.hub.start();

        chat.client.addNewMessageToPage = function (message, connectionid) {
            debugger;
            console.info("11"+connectionid);
            $('.dropdown-menu .listview .lv-body', parent).prepend('<a class="lv-item" href="#">' +
                                                             '<div class="media">' +
                                                             '<div class="pull-left">' +
                                                             '<img class="lv-img-sm" src="img/profile-pics/1.jpg" alt="">' +
                                                             '</div>' +
                                                             ' <div class="media-body">' +
                                                             '<div class="lv-title">E-imza</div>' +
                                                             '<small class="lv-small">' + message + '</small>' +
                                                             '</div>' +
                                                             '</div>' +
                                                             '</a>');


        };
        $.connection.hub.start().done(function () {
            debugger;
        });

    });
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }



    //});

Where static method has been called in another MVC controller

[HttpPost]
        public ActionResult BasvuruCreate(Ruhsat model)
        {
ChatHub.Static_Send("aa", item.identity);

}

You need following:

  1. A method on server to send a message to single client with client ID. This would be similar to sendProxy but this time instead of ALL you need to select connectionID (or for signalR 2.0 you can use iUserIdProvider as stated here by example passed to it.
  2. You can use AddMessagetoPage function on client to add message or you can use different method of adding a private user message as well.

If you understand the cycle of Send and read through https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections you will find that connectionID may not be best to keep hold of and you have username or something that would then resolve into client ID and then you send a message to them. You can try this with connection ID to at least resolve the problem that code is working with known connection IDs.

You have OnConnected method where you have obtained both connectionID and username but you are not storing it anywhere so if a user connects from mobile and desktop the username is same but connection IDs are different. Similarly if a user logs in from chrome and IE both then you will have two connection IDs and one username. You will need to resolve this so from username obtain an array of connection IDs then then call client side method to send whatever you want to that hub.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM