简体   繁体   中英

Signal R Live Chat Application in MVC

I want to create Live Chat application using SignalR in ASP.NET MVC. I have created this but the problem is it is sending message to all the users who are connected to that server. I only want to have private chat between two users. So please help me out. Here is my Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

//this is ChatHub.cs file
namespace LiveChat
{
public class ChatHub : Hub
{
    public override System.Threading.Tasks.Task OnConnected()
    {
        Clients.Caller.user(Context.User.Identity.Name);
        return base.OnConnected();
    }
    public void send(string message)
    {
        Clients.Caller.message("You:" + message);         
        Clients.Others.message(Context.User.Identity.Name + ": " + message);

    }

}}

//This is Startup class

using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(LiveChat.Startup))]
namespace LiveChat
{
public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        app.MapSignalR();
    }
}
}

//This is my js
 <script>
var hub = $.connection.chatHub;
hub.client.message = function (msg) {
$("#message").append("<li>" + msg + "</li>")
}

hub.client.user = function (msg) {
$("#user").append("<li>" + msg + "</li>")
}
$.connection.hub.start(function () {
$("#send").click(function () {
    if ($("#txt").val() == "") {
        return;
    }
    hub.server.send($("#txt").val());
    $("#txt").val(" ");
});
$("#txt").keyup(function (event) {
    if ($("#txt").val() == "") {
        return;
    }
    if (event.keyCode == 13) {
        hub.server.send($("#txt").val());
    }
});
});
</script>

you can use a static list , the list contains all client that connected to the hub and their connection id, on send message, you have to the hub the text and the destination member. and than send to the specific memeber.

add the member to the list in the function OnConnected, the client id :

Context.clientID

send to specific client in function send

var clientId = ""; // get from the static list by id you got
var scbscriber = Clients.Client(clientId);
scbscriber.message(text);
public class ChatHub : Hub
{
    private static List<Users> ConnectedUsers;

    public ChatHub()
    {
        ConnectedUsers = new List<Users>();
    }

    public override System.Threading.Tasks.Task OnConnected()
    {
        Clients.Caller.user(Context.User.Identity.Name);
        ConnectedUsers.Add(new Users(){
            UserName = Context.User.Identity.Name,
            ClientId = Context.clientID;
        });
        return base.OnConnected();
    }
    public void send(string message, string UserName)
    {

        //Clients.Caller.message("You:" + message); 
        var clientId = ConnectedUsers.FirstOrDefulat(x=>x.UserName == UserName).ClientId; // get from the static list by id you got     
        var scbscriber = Clients.Client(clientId);
        scbscriber.message(Context.User.Identity.Name + ": "message);

        //Clients.Others.message(Context.User.Identity.Name + ": " + message);

    }

}
public class Users
    {
          public string UserName{get;set;}
          public string ClientId {get;set;}
    }

Here you go mate:

 public void SendPrivateMessage(Messaging objMessaging)
    {
        var fromNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.FromNurseId);
        var toNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.ToNurseId);
        var chatObject = new { MessageThreadId = 0, Name = fromNurse.NurseName, Message = objMessaging.Message,  DTStmp = DateTime.Now, frmNurseId = fromNurse.NurseId };

        Result objResult = objMessagingDAL.InsertMessage(objMessaging);

        if (toNurse != null)
        {
            Clients.Client(toNurse.ConnectionId).ReceivePrivateMessage(chatObject);
        }
        Clients.Caller.ReceivePrivateMessage(chatObject);

    }

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