65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET WebForm 和 BootStrap 结合 SignalR 实现的聊天应用 - 第二部分

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.94/5 (25投票s)

2018 年 1 月 2 日

CPOL

4分钟阅读

viewsIcon

30839

downloadIcon

4376

在实时聊天应用中集成 SignalR 与 ASP.NET C# WebForm 应用

引言

在上一篇文章中,我们学习了如何使用 SignalR 创建一个实时聊天应用程序。到目前为止,我们已经学习了 SignalR 和 Bootstrap 的集成以及群聊的创建。在这篇文章中,我们将添加一些功能,例如私聊、通知系统、消息计数和清除聊天功能等。

添加这些功能后,我们的应用程序将更具交互性,您将更多地了解 SignalR 和 Jquery,了解如何在 HUB 类中创建函数,或者如何使用 Jquery 从客户端调用这些 Hub 类函数,以及如何使用 Jquery 动态生成 HTML 代码并将其附加到现有的 HTML Div

对于错过了上一篇文章的读者,请参考上一篇文章“ASP.NET WebForm 和 BootStrap 结合 SignalR 实现的聊天应用 - 第一部分”,同时也可以 下载 项目文件,我们将基于上一篇文章的项目文件继续。

创建私聊

由于我们将继续使用上一个项目,首先我们要添加“私聊”。我们已经有了在线用户列表,所以在这里我们需要为私聊创建 HTML 设计,稍后我们将使用这个设计进行私聊。我们将把新的 DIV 添加到群聊 DIV 之后,HTML 代码将是:

<div class="row">
    <div class="col-md-12">
        <div class="row" id="PriChatDiv">
        </div>
        <textarea class="form-control" style="visibility: hidden;"></textarea>
        <!--/.private-chat -->
    </div>
</div>

在设计文件中添加完上述 HTML 代码后,我们将编写代码来创建和打开私聊框。我们已经为带有各自 ID 的用户名提供了链接,因此将根据用户 ID 创建和打开私聊框。通过将以下代码添加到我们的 Jquery 函数“AddUser”中:

 var UserLink = $('<a id="' + id +
'" class="user" >' + name + '<a>');
                $(code).click(function () {

                    var id = $(UserLink).attr('id');

                    if (userId != id) {
                        var ctrId = 'private_' + id;
                        OpenPrivateChatBox(chatHub, id, ctrId, name);
                    }
                });

现在我们将编写 Jquery 代码来生成私聊 DIV 的动态 HTML 代码,并将其附加到“PriChatDivDiv 中。它将根据 HUB 生成的用户 ID 创建私聊框,因此在在线用户列表中点击用户名时,它将为每个用户打开一个单独的聊天框。

用于创建和打开私聊 DIV 的 JavaScript 代码

// Creation and Opening Private Chat Div
        function OpenPrivateChatBox(chatHub, userId, ctrId, userName) {

            var PWClass = $('#PWCount').val();

            if ($('#PWCount').val() == 'info')
                PWClass = 'danger';
            else if ($('#PWCount').val() == 'danger')
                PWClass = 'warning';
            else
                PWClass = 'info';

            $('#PWCount').val(PWClass);
            var div1 = ' <div class="col-md-4"> <div  id="' + ctrId +
             '" class="box box-solid box-' + PWClass + ' direct-chat direct-chat-' + PWClass + '">' +
                '<div class="box-header with-border">' +
                ' <h3 class="box-title">' + userName + '</h3>' +

                ' <div class="box-tools pull-right">' +
                ' <span data-toggle="tooltip" id="MsgCountP" title="0 New Messages"
                '  class="badge bg-' + PWClass + '">0</span>' +
                ' <button type="button" class="btn btn-box-tool" data-widget="collapse">' +
                '    <i class="fa fa-minus"></i>' +
                '  </button>' +
                '  <button id="imgDelete" type="button" class="btn btn-box-tool" data-widget="remove">
                '  <i class="fa fa-times"></i></button></div></div>' +

                ' <div class="box-body">' +
                ' <div id="divMessage" class="direct-chat-messages">' +

                ' </div>' +

                '  </div>' +
                '  <div class="box-footer">' +

                '    <input type="text" id="txtPrivateMessage"
                '     name="message" placeholder="Type Message ..." class="form-control"  />' +

                '  <div class="input-group">' +
                '    <input type="text" name="message" placeholder="Type Message ..."
                '     class="form-control" style="visibility:hidden;" />' +
                '   <span class="input-group-btn">' +
                '          <input type="button" id="btnSendMessage"
                '           class="btn btn-' + PWClass + ' btn-flat" value="send" />' +
                '   </span>' +
                '  </div>' +

                ' </div>' +
                ' </div></div>';

            var $div = $(div1);

            // Closing Private Chat Box
            $div.find('#imgDelete').click(function () {
                $('#' + ctrId).remove();
            });

            // Send Button event in Private Chat
            $div.find("#btnSendMessage").click(function () {

                $textBox = $div.find("#txtPrivateMessage");

                var msg = $textBox.val();
                if (msg.length > 0) {
                    chatHub.server.sendPrivateMessage(userId, msg);
                    $textBox.val('');
                }
            });

            // Text Box event on Enter Button
            $div.find("#txtPrivateMessage").keypress(function (e) {
                if (e.which == 13) {
                    $div.find("#btnSendMessage").click();
                }
            });

            // Clear Message Count on Mouse over
            $div.find("#divMessage").mouseover(function () {

                $("#MsgCountP").html('0');
                $("#MsgCountP").attr("title", '0 New Messages');
            });

            // Append private chat div inside the main div
            $('#PriChatDiv').append($div);
        }

在上面的代码中,我们正在创建一个用于私聊的 div,这里有一个用于关闭聊天框的按钮,我们还在聊天框标题栏的消息计数器中显示新消息的数量。鼠标悬停时也会清除消息计数器。如果消息数量过多超出 div 的空间,我们将为聊天 div 应用滚动条。每次打开聊天框时,我们还会为 div 应用不同的 CSS 样式。

私聊消息发送代码

chatHub.client.sendPrivateMessage = 
function (windowId, fromUserName, message, userimg, CurrentDateTime) {

    var ctrId = 'private_' + windowId;
    if ($('#' + ctrId).length == 0) {
    
        OpenPrivateChatBox(chatHub, windowId, ctrId, fromUserName, userimg);
        
    }
    
    var CurrUser = $('#hdUserName').val();
    var Side = 'right';
    var TimeSide = 'left';
    
    if (CurrUser == fromUserName) {
        Side = 'left';
        TimeSide = 'right';
        
    }
    else {
        var Notification = 'New Message From ' + fromUserName;
        IntervalVal = setInterval("ShowTitleAlert('SignalR Chat App', 
                      '" + Notification + "')", 800);
        
        var msgcount = $('#' + ctrId).find('#MsgCountP').html();
        msgcount++;
        $('#' + ctrId).find('#MsgCountP').html(msgcount);
        $('#' + ctrId).find('#MsgCountP').attr("title", msgcount + ' New Messages');
    }
    
    var divChatP = '<div class="direct-chat-msg ' + Side + '">' +
        '<div class="direct-chat-info clearfix">' +
        '<span class="direct-chat-name pull-' + Side + '">' + fromUserName + 
        '</span>' +
        '<span class="direct-chat-timestamp pull-' + TimeSide + '"">' + CurrentDateTime + 
        '</span>' +
        '</div>' +
        
        ' <img class="direct-chat-img" src="' + userimg + 
        '" alt="Message User Image">' +
        ' <div class="direct-chat-text" >' + message + 
        '</div> </div>';
        
    $('#' + ctrId).find('#divMessage').append(divChatP);
    
    var htt = $('#' + ctrId).find('#divMessage')[0].scrollHeight;
    $('#' + ctrId).find('#divMessage').slimScroll({
        height: htt
    });
}

在这里,我们通过 JavaScript 调用“SendPrivateMessage”函数,该函数已添加到我们命名为“ChatHub.cs”的 Hub 类中。

ChatHub.cs 类文件代码

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)
    {
        string CurrentDateTime = DateTime.Now.ToString();
        string UserImg = GetUserImage(fromUser.UserName);
        // send to
        Clients.Client(toUserId).sendPrivateMessage
             (fromUserId, fromUser.UserName, message, UserImg, CurrentDateTime);
        // send to caller user
        Clients.Caller.sendPrivateMessage
             (toUserId, fromUser.UserName, message, UserImg, CurrentDateTime);
    }
}

至此,私聊的集成已完成。运行项目,查看输出,输出将如下所示:

创建标题栏提示

在这里,我们将集成标题栏提示系统,就像 Facebook 一样,当我们收到在线用户的消息时,它将在页面标题栏显示通知。我们这里使用 JavaScript 简单地实现了通知。

IntervalVal = setInterval("ShowTitleAlert
('SignalR Chat App', '" + Notification + "')", 1000);

我们正在以 1000ms 的间隔调用“ShowTitleAlert”函数,因此它将在设定的时间间隔内显示消息提示。当窗口获得焦点时,它将中断/清除间隔。

// Show Title Alert
        function ShowTitleAlert(newMessageTitle, pageTitle) {
            if (document.title == pageTitle) {
                document.title = newMessageTitle;
            }
            else {
                document.title = pageTitle;
            }
        }

清除聊天记录

用户可以根据需要清除旧的聊天记录。为了清除聊天记录,我们在群聊框的顶部标题栏添加了清除聊天图标。在私聊中,我们可以通过关闭聊天框来清除聊天,但在群聊中,我们无法关闭聊天框,因此我们提供了清除聊天的选项。

Hub 类中创建一个用于清除聊天的函数

// Clear Chat History
        public void clearTimeout()
        {
            CurrentMessage.Clear();
        }

用于清除聊天的 Jquery 代码,我们正在从 Hub 类调用函数并清除聊天 div

 // Clear Chat
        $('#btnClearChat').click(function () {

            var msg = $("#divChatWindow").html();

            if (msg.length > 0) {
                chatHub.server.clearTimeout();
                $('#divChatWindow').html('');

            }
        });

输出

现在运行项目,最终输出将如下所示:

结论

在这里,您将学习 SignalR 私聊的集成和使用 JavaScript 创建标题栏提示,添加消息计数器。我们首先在 HUB 类中创建函数,然后调用这些函数到 Jquery 函数中,动态生成 HTML 代码并将其附加到现有的 HTML DIV。在创建 ChatBox 时,每次应用不同的 CSS 样式。这是“SignalR 聊天应用”教程的第二部分。在我**下一篇文章**中,我将向您展示**表情符号**在聊天中的集成,使我们的聊天应用程序更具交互性。我们还将集成**通过聊天发送附件**,发送图片文件并在聊天中下载或显示图片。

希望这对您有所帮助,并且您喜欢这篇文章。我已附上项目源代码。您可以下载源代码供您参考并查看完整源代码。感谢您的阅读...

请在评论区留下您宝贵的反馈。

© . All rights reserved.