简体   繁体   中英

How Can I Send Message To specific User with signalR

I have some problem with signalR, I can not send message to specific User From Hub.

I want to do like this:

public void Send(string userToId, string userForId, string message)
{

    IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHubs>();

    //userForId - it is Session["UserId"]
    context.Clients.User(userForId).updateMessages(message);
}

I have already read this topic: http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections , but It's not clear for me, because I have not this var name = Context.User.Identity.Name; I have User information in Session Variable and second when I get connectionId like this: var myClientId = $.connection.hub.id; connectionId -is changed when I refresh page or when I click another menu on my project.

I have some questions: 1) Can I send message to specific user without connectionId (use only session["UserId"]) ? 2) In General, How can I make easily one-to-one messaging with SignalR ?

PS I'm working ASP.NET MVC (C#)

You can send broadcast message to all Users without connection id. You just need to assign a Unique ID to Every user and Send it as Message parameters.

SignalR Gives a Unique ID to Every Client as connection ID. Either you can use that connection Id or you can assign unique ID to client while creating client and use it as Connection ID. thats up to you what you want to Use.

Edit

Just Update Your Your Method in your Hub Class File.....

     public void Send(string name, string message, string connectionid)
{
    // Call the addNewMessageToPage method to update clients.
    Clients.All.addNewMessageToPage(name, message, connectionid);
}

And In Your Client Side You can Update Add Code After including SignalR Files:-

        var chat = $.connection.chatHub;


             chat.client.addNewMessageToPage = function (name, message, connectionid) {
            if (connectionid == $('#connection').val()) {

               //   Do What You want Here...
            };
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val(prompt('Enter your name:', ''));
        $('#connection').val(prompt('Enter your ID:', ''));

        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                // Call the Send method on the hub.
                chat.server.send($('#displayname').val(), $('#message').val(), $('#connection').val());
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        });

Hope This Helps...

If you want to send message to specific user in SignalR, easiest way is the use Form authentication. Also you can use your custom session with form authentication. Right after creation your session code put this code.

FormsAuthentication.SetAuthCookie(username.Trim(), false);

Then in signalR you can use this line for send message to this user:

var username = Context.User.Identity.Name;
context.Clients.User(username).updateMessages(message);

EDIT:

For your question pass username to this method (receiver username) and push message to that user.Then you dont need to give a userForId, because you already have sender username with "var username = Context.User.Identity.Name;".Also this method will just push to method that receiver user name. If you want to get also message to sender you need to user "Caller" and you need a write new function to get caller messages in javascript.I hope its clear for you.

public void Send(string username, string message)
{
    context.Clients.Caller.updateMessagesCaller(message);
    context.Clients.User(username).updateMessages(message);
}

This message will go only that username.And my recommendation is use FormAuthentication implementation in your whole project.Thanks.

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