locked
Chat Application using SignalR RRS feed

  • Question

  • User-1051479001 posted

    Hi Guys,

    I am very new to the signalR, can any one please explain how to create multiple chat rooms (group chats) in SignalR using MVC or WebApi.I want to create on chat application for my project.. so that i am looking for it.

    So, please respond me ASAP,

    Thanks in Advance,

    Hemanth.

    Monday, March 6, 2017 5:43 AM

Answers

All replies

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 6, 2017 5:53 AM
  • User-1051479001 posted

    Hi KathyW,

    Thanks for your amazing response,

    Hemanth.

    Monday, March 6, 2017 6:07 AM
  • User-1838255255 posted

    Hi hemanth komanduri,

    According to your description, you say very new to signalr, I think you could start with the here.

    Here are two samples about use signalr to make a chat application in MVC.

    Real Time Web Solution for Chat by MVC SignalR Hub:

    https://www.codeproject.com/Articles/732190/Real-Time-Web-Solution-for-Chat-by-MVC-SignalR-H

    This tutorial shows how to use ASP.NET SignalR 2 to create a real-time chat application. You will add SignalR to an MVC 5 application and create a chat view to send and display messages:

    https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr-and-mvc 

    Best Regards,

    Eric Du

    Tuesday, March 7, 2017 2:48 AM
  • User-1051479001 posted

    Hi Eric Du,

    Thanks for your valuable suggestion,

    And also please suggest some multiple groups chat examples.. need to be the major in my project... I have seen some examples like the below link 

    https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups

    but I don't know how to implement this scenario, suggestions can u please give some suggestions for this,

    Thanks in Advance,

    Hemanth

    Tuesday, March 7, 2017 4:45 AM
  • User-1838255255 posted

    Hi hemanth komanduri,

    but I don't know how to implement this scenario, suggestions can u please give some suggestions for this,

    I think this tutorial's introduce is very clear, I am not clear what's bothering you, I hope you could give us more detail description about what make you confused, also I hope you could try this tutorial, any issue you could post when you trying!

    Best Regards,

    Eric Du

    Tuesday, March 7, 2017 8:05 AM
  • User-1051479001 posted

    Hi Eric,

    this the code I am using for chat app in this code I am getting the public chat room and private chat for different users.. so, for this, I need multiple group chat rooms can u please help me how to get the multiple chat rooms,

    HTML Code:

    div id="header">
            SignalR Chat Room
        </div>
        <br />
        <br />
        <br />
     
        <div id="divContainer">
            <div id="divLogin" class="login">
                <div>
                    Your Name:<br />
                    <input id="txtNickName" type="text" class="textBox" />
                </div>
                <div id="divButton">
                    <input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
                </div>
            </div>
     
            <div id="divChat" class="chatRoom">
                <div class="title">
                    Welcome to Chat Room [<span id='spanUser'></span>]
     
                </div>
                <div class="content">
                    <div id="divChatWindow" class="chatWindow">
                    </div>
                    <div id="divusers" class="users">
                    </div>
                </div>
                <div class="messageBar">
                    <input class="textbox" type="text" id="txtMessage" />
                    <input id="btnSendMsg" type="button" value="Send" class="submitButton" />
                </div>
            </div>
     
            <input id="hdId" type="hidden" />
            <input id="hdUserName" type="hidden" />
        </div>


    JavaScript Code:

    <script type="text/javascript">
     
        $(function () {
     
            setScreen(false);
     
            // Declare a proxy to reference the hub.
            var chatHub = $.connection.chatHub;
     
            registerClientMethods(chatHub);
     
            // Start Hub
            $.connection.hub.start().done(function () {
     
                registerEvents(chatHub)
     
            });
     
        });
     
        function setScreen(isLogin) {
     
            if (!isLogin) {
     
                $("#divChat").hide();
                $("#divLogin").show();
            }
            else {
     
                $("#divChat").show();
                $("#divLogin").hide();
            }
     
        }
     
        function registerEvents(chatHub) {
     
            $("#btnStartChat").click(function () {
     
                var name = $("#txtNickName").val();
                if (name.length > 0) {
                    chatHub.server.connect(name);
                }
                else {
                    alert("Please enter name");
                }
     
            });
     
    
            $('#btnSendMsg').click(function () {
     
                var msg = $("#txtMessage").val();
                if (msg.length > 0) {
     
                    var userName = $('#hdUserName').val();
                    chatHub.server.sendMessageToAll(userName, msg);
                    $("#txtMessage").val('');
                }
            });
     
    
            $("#txtNickName").keypress(function (e) {
                if (e.which == 13) {
                    $("#btnStartChat").click();
                }
            });
     
            $("#txtMessage").keypress(function (e) {
                if (e.which == 13) {
                    $('#btnSendMsg').click();
                }
            });
     
    
        }
     
        function registerClientMethods(chatHub) {
     
            // Calls when user successfully logged in
            chatHub.client.onConnected = function (id, userName, allUsers, messages) {
     
                setScreen(true);
     
                $('#hdId').val(id);
                $('#hdUserName').val(userName);
                $('#spanUser').html(userName);
     
                // Add All Users
                for (i = 0; i < allUsers.length; i++) {
     
                    AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
                }
     
                // Add Existing Messages
                for (i = 0; i < messages.length; i++) {
     
                    AddMessage(messages[i].UserName, messages[i].Message);
                }
     
    
            }
     
            // On New User Connected
            chatHub.client.onNewUserConnected = function (id, name) {
     
                AddUser(chatHub, id, name);
            }
     
    
            // On User Disconnected
            chatHub.client.onUserDisconnected = function (id, userName) {
     
                $('#' + id).remove();
     
                var ctrId = 'private_' + id;
                $('#' + ctrId).remove();
     
    
                var disc = $('<div class="disconnect">"' + userName + '" logged off.</div>');
     
                $(disc).hide();
                $('#divusers').prepend(disc);
                $(disc).fadeIn(200).delay(2000).fadeOut(200);
     
            }
     
            chatHub.client.messageReceived = function (userName, message) {
     
                AddMessage(userName, message);
            }
     
    
            chatHub.client.sendPrivateMessage = function (windowId, fromUserName, message) {
     
                var ctrId = 'private_' + windowId;
     
    
                if ($('#' + ctrId).length == 0) {
     
                    createPrivateChatWindow(chatHub, windowId, ctrId, fromUserName);
     
                }
     
                $('#' + ctrId).find('#divMessage').append('<div class="message"><span class="userName">' + fromUserName + '</span>: ' + message + '</div>');
     
                // set scrollbar
                var height = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
                $('#' + ctrId).find('#divMessage').scrollTop(height);
     
            }
     
        }
     
        function AddUser(chatHub, id, name) {
     
            var userId = $('#hdId').val();
     
            var code = "";
     
            if (userId == id) {
     
                code = $('<div class="loginUser">' + name + "</div>");
     
            }
            else {
     
                code = $('<a id="' + id + '" class="user" >' + name + '<a>');
     
                $(code).dblclick(function () {
     
                    var id = $(this).attr('id');
     
                    if (userId != id)
                        OpenPrivateChatWindow(chatHub, id, name);
     
                });
            }
     
            $("#divusers").append(code);
     
        }
     
        function AddMessage(userName, message) {
            $('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
     
            var height = $('#divChatWindow')[0].scrollHeight;
            $('#divChatWindow').scrollTop(height);
        }
     
        function AddDivToContainer($div) {
            $('#divContainer').prepend($div);
     
            $div.draggable({
     
                handle: ".header",
                stop: function () {
     
                }
            });
        }
     
    </script>


    C# code
    public class ChatHub : Hub
        {
            #region List of Data Member 
    
            static List<UserDetail> ConnectedUsers = new List<UserDetail>();
            static List<MessageDetail> CurrentMessage = new List<MessageDetail>();
     
            #endregion
    
     
            #region Send, recieve and broadcast message methods
    
            public void Connect(string userName)
            {
                // To get the clients connected connection ID's
                var id = Context.ConnectionId;
                if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
                {
                    ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserName = userName });
     
                    // send to caller
                    Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage);
     
                    // send to all except caller client
                    Clients.AllExcept(id).onNewUserConnected(id, userName);
                }
            }
            // To send message to all the connected clients
            public void SendMessageToAll(string userName, string message)
            {
                // store last 100 messages in cache
                AddMessageinCache(userName, message);
     
                // Broad cast message
                Clients.All.messageReceived(userName, message);
            }
            public void SendPrivateMessage(string toUserId, string message)
            {
     
                string fromUserId = Context.ConnectionId;
     
                var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId);
                var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);
     
                if (toUser != null && fromUser != null)
                {
                    // send to 
                    Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.UserName, message);
     
                    // send to caller user
                    Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
                }
     
            }
     
            public override System.Threading.Tasks.Task OnDisconnected()
            {
                var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
                if (item != null)
                {
                    ConnectedUsers.Remove(item);
     
                    var id = Context.ConnectionId;
                    Clients.All.onUserDisconnected(id, item.UserName);
     
                }
     
                return base.OnDisconnected();
            }
     
            #endregion
    
     
            #region private Messages send to individual
            private void AddMessageinCache(string userName, string message)
            {
                CurrentMessage.Add(new MessageDetail { UserName = userName, Message = message });
     
                if (CurrentMessage.Count > 100)
                    CurrentMessage.RemoveAt(0);
            }
            #endregion
        }


    Two Other Classes:

    public class MessageDetail
        {
            public string UserName { get; set; }
            public string Message { get; set; }
        }
    public class UserDetail
        {
            public string ConnectionId { get; set; }
            public string UserName { get; set; }
        }

    Please help me

     Thanks,

    Hemanth

    Wednesday, March 8, 2017 9:14 AM
  • User-1838255255 posted

    Hi hemanth komanduri,

    As far as I know, you could use Groups.add method to operate this function! Here is someone who meet the similar problem as you:

    SignalR multiple chat rooms:

    http://stackoverflow.com/questions/11175173/signalr-multiple-chat-rooms?rq=1

    Working with Groups in SignalR:

    https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups 

    Best Regards,

    Eric Du

    Thursday, March 9, 2017 9:35 AM
  • User-1051479001 posted

    Hi Eric,

    Thanks for your suggestions,

    Can u please help me, How to create a Group?  

    Thanks, 

    Hemanth. 

    Monday, March 13, 2017 6:09 AM