Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

multiple group chat rooms in asp.net using signalR

$
0
0

I am implementing a chat server using signal for multiple groups chat room. for demo see here like chat.stackoverflow.com
But my code is working for only single chat room. anyone can tell how to create multiple chat rooms. My code is here:

HTML Code:

div id="header">
        SignalR Chat Room</div><br/><br/><br/> <divid="divContainer"><divid="divLogin"class="login"><div>
                Your Name:<br/><inputid="txtNickName"type="text"class="textBox"/></div><divid="divButton"><inputid="btnStartChat"type="button"class="submitButton"value="Start Chat"/></div></div> <divid="divChat"class="chatRoom"><divclass="title">
                Welcome to Chat Room [<spanid='spanUser'></span></div><divclass="content"><divid="divChatWindow"class="chatWindow"></div><divid="divusers"class="users"></div></div><divclass="messageBar"><inputclass="textbox"type="text"id="txtMessage"/><inputid="btnSendMsg"type="button"value="Send"class="submitButton"/></div></div> <inputid="hdId"type="hidden"/><inputid="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 Usersfor (i = 0; i < allUsers.length; i++) { 
                AddUser(chatHub, allUsers[i].ConnectionId, allUsers[i].UserName);
            } // Add Existing Messagesfor (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 scrollbarvar 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>


SignalR C# Code:

publicclass 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 methodspublicvoid Connect(string userName)
        {// To get the clients connected connection ID'svar 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 clientspublicvoid SendMessageToAll(string userName, string message)
        {// store last 100 messages in cache            AddMessageinCache(userName, message); // Broad cast message            Clients.All.messageReceived(userName, message);
        }publicvoid 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);
            } 
        } publicoverride 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); 
            } returnbase.OnDisconnected();
        } #endregion #region private Messages send to individualprivatevoid AddMessageinCache(string userName, string message)
        {
            CurrentMessage.Add(new MessageDetail { UserName = userName, Message = message }); if (CurrentMessage.Count > 100)
                CurrentMessage.RemoveAt(0);
        }#endregion    }


Two Other Classes:

publicclass MessageDetail
    {publicstring UserName { get; set; }publicstring Message { get; set; }
    }
publicclass UserDetail
    {publicstring ConnectionId { get; set; }publicstring UserName { get; set; }
    }

Please help me if anyone known this.


Viewing all articles
Browse latest Browse all 9386

Trending Articles