Home > Mobile >  How can I make one to one chat system in Asp.Net.Core Mvc Signalr?
How can I make one to one chat system in Asp.Net.Core Mvc Signalr?

Time:09-18

I want to implement private chat system with Mssql Database. This codes works as public when I send the message, message is appears all clients. But I want to one to one chat system. One user enter the receiver id which stored in database and message text, then send the message to Receiver . Then the message appears in receiver message area which has that receiver id.

Here is my js code

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chathub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.start().then(function () {
    document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendButton").addEventListener("click", function (event) {
    var user = document.getElementById("userInput").value;
    var message = document.getElementById("messageInput").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});
connection.on("ReceiveMessage", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user   ":"   msg;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

Here is my hub class

using MentorShip.Models;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;

using System.Threading.Tasks;

namespace MentorShip.Hubs
{
    public class SignalRChat:Hub
    {
        Context c = new Context();
        
        public async Task SendMessage(string user, string message)
        {
           
            await  Clients.All.SendAsync("ReceiveMessage",user,message);
        }

    }
}

Here is my html code

            <div class="container">
            <div class="row">&nbsp;</div>
            <div class="row">
                <div id="connectionId"></div>
                <div class="col-2">Receiver Id</div>
                <div class="col-4"><input type="text" id="userInput" /></div>
            </div>
            <div class="row">
                <div class="col-2">Message</div>
                <div class="col-4"><input type="text" id="messageInput" /></div>
            </div>
            <div class="row">&nbsp;</div>
            <div class="row">
                <div class="col-6">
                    <input type="button" id="sendButton" value="Send Message" />
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-12">
                <hr />
            </div>
        </div>
        <div class="row">
            <div class="col-6">
                <ul id="messagesList"></ul>
            </div>
        </div>
    </div>

CodePudding user response:

To send the message to specific user, you could use the following methods:

  1. Use Single-user groups.

    You can create a group for each user, and then send a message to that group when you want to reach only that user. The name of each group is the name of the user. If a user has more than one connection, each connection id is added to the user's group.

    For example, base on the enter image description here

  2. Send message via the ConnectionID.

    From the above sample code, in the OnConnectedAsyc method, we could get the ConnectId and the User Name, then, you could store them in the database. Then, you can add the SendMessageToUser method in the ChatHub.cs. In this method, you could query the database and find the connectionId based on the receiver name, after that using Clients.Client("connectionId").SendAsync() method to send the message to a specific user.

     public Task SendMessageToUser(string sender, string receiver, string message)
     {
         //based on the receiver name to query the database and get the connection id
    
         return Clients.Client("connectionId").SendAsync("ReceiveMessage", sender, message);
     }
    

Here are some related articles, you can refer to them:

enter image description here

  • Using the following command in the Package Manager Console tools. More detail information, check enter image description here

  • Add the SignalR client library

    • In Solution Explorer, right-click the project, and select Add > Client-Side Library.
    • In the Add Client-Side Library dialog, for Provider select unpkg.
    • For Library, enter @microsoft/signalr@latest.
    • Select Choose specific files, expand the dist/browser folder, and select signalr.js and signalr.min.js.
    • Set Target Location to wwwroot/js/signalr/, and select Install. LibMan creates a wwwroot/js/signalr folder and copies the selected files to it.
  • Create a SignalR hub.

    In the Project folder, create a Hubs folder and add a ChatHub.cs file with the following code:

     namespace SignalRApp.Hubs
     {
         //require using Microsoft.AspNetCore.SignalR;
         //require using Microsoft.AspNetCore.Authorization;
         [Authorize]
         public class ChatHub : Hub
         {
             public override Task OnConnectedAsync()
             {
                 Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
                 return base.OnConnectedAsync();
             }
             public async Task SendMessage(string user, string message)
             {
                 await Clients.All.SendAsync("ReceiveMessage", user, message);
             }
    
             public Task SendMessageToGroup(string sender, string receiver, string message)
             {
                 return Clients.Group(receiver).SendAsync("ReceiveMessage", sender, message);
             }
         }
     }
    
  • Configure SignalR in the Startup.cs file. You could check enter image description here

    • Related