Search code examples
asp.net-coreasp.net-core-mvcsignalrsignalr-hubsignalr.client

How to send Message only Two user in SignalR


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


Solution

  • 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 document.

    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 this code 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