How to send Message only Two user in SignalR

Viewed 83

I want when I send message to one another two will got that message like signalR groups but I doesn't use group I do this thing without group

Please Anyone can tell how to do that

1 Answers

You could try

public async Task SendMessage(string user, string message)
        {
            
            await Clients.Others.SendAsync("ReceiveMessage", user, message);
        }

I tried with the codes in this document,just modified the codes in hub And the result: enter image description here

Send message to specific user you could check this ducument:

Update:

I add the codes in chat.js:

document.getElementById("sendButton1").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage1", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

add another button in page:

<div class="col-6">
            <input type="button" id="sendButton1" value="Send Message" />
        </div>

Add the codes in Hub:

public async Task SendMessage1(string user, string message)
        {
            var a = Context.UserIdentifier;
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }

Result: enter image description here

Related