ASP.NET+SignalR聊天室

源码下载:https://pan.baidu.com/s/1l_XNjpGrrhrx9fz0MXQHLQ  提取码: pr8q

Nuget里搜索安装SignalR,非ASP.NET CORE版本。

1.增加Startup类

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(CHATROOM.Startup))]

namespace CHATROOM
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
            app.MapSignalR();
        }
    }
}

2.增加继承自Hub的类

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace CHATROOM
{
    [HubName("CHATROOM")]
    public class BaseHub : Hub
    {
        public static Dictionary<string, string> onlineList = new Dictionary<string, string>();
        public override Task OnConnected()
        {
            string username = Context.QueryString["username"].ToString();
            onlineList.Add(Context.ConnectionId, username);
            Clients.All.onLine(username, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), onlineList.ToList());
            return base.OnConnected();
        }
        public override Task OnDisconnected(bool stopCalled)
        {
            string username = Context.QueryString["username"].ToString();
            onlineList.Remove(Context.ConnectionId);
            Clients.All.offLine(username, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), onlineList.ToList());
            return base.OnDisconnected(stopCalled);
        }
        public void Send(string username, string message, string sendto)
        {
            message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>");
            if (string.IsNullOrWhiteSpace(sendto))
            {
                Clients.All.receiveMessage(username, message, sendto, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                List<string> connids = sendto.Split(',').ToList();
                var st = string.Join(",", onlineList.Where(o => connids.Contains(o.Key)).Select(o => o.Value));
                Clients.Caller.receiveMessage(username, message, st, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                Clients.Clients(connids).receiveMessage(username, message, st, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }
    }

}

3.前端代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="CHATROOM.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.4.1.min.js"></script>
    <script>
        $(function () {

            var username = $("#lbUsername").text();
            var hub = $.hubConnection();
            hub.qs = { "username": username };
            var chat = hub.createHubProxy("CHATROOM");

            hub.start().done(function () {
                $("#btnSend").click(function () {
                    var username = $("#lbUsername").text();
                    var sendto = $("#lbSendtoUser").attr("connid");
                    var msg = $("#txtMsg").val();
                    if (!username) return;
                    chat.invoke("send", username, msg, sendto)
                    .done(function () {
                        $("#txtMsg").val(""); //发送成功
                    }).fail(function (e) {
                        alert(e); //发送失败
                    })
                })
            })

            var updateUserlist = function (onlineList) {
                $("#olUserlist").html("");
                for (var i = 0; i < onlineList.length; i++) {
                    var key = onlineList[i]["Key"];
                    var name = onlineList[i]["Value"];
                    var li = '<li class="userItem"><a onclick="selUser(\'' + key + '\', \'' + name + '\')">' + name + '</a></li>';
                    $("#olUserlist").append(li);
                }
            }
            chat.on("onLine", function (username, time, onlineList) {
                $(".msgBox").append("<div><span class='user'>" + username + "</span> 加入群聊 <span class='time'>" + time + "</span></div>");
                $(".msgBox").scrollTop($(".msgBox")[0].scrollHeight);
                updateUserlist(onlineList)
            })
            chat.on("offLine", function (username, time, onlineList) {
                $(".msgBox").append("<div><span class='user'>" + username + "</span> 退出群聊 <span class='time'>" + time + "</span></div>");
                $(".msgBox").scrollTop($(".msgBox")[0].scrollHeight);
                updateUserlist(onlineList)
            })
            chat.on("receiveMessage", function (username, msg, sendto, time) {
                var st = " ";
                if (sendto) st = " <span class='sendto'>@"+sendto+"</span> ";
                $(".msgBox").append("<div><span class='user'>" + username + "</span>" + st + "<span class='time'>" + time + "</span></div>");
                $(".msgBox").append("<div><span>" + msg + "</span></div>");
                $(".msgBox").scrollTop($(".msgBox")[0].scrollHeight);
            })

            $("#btnClear").click(function () {
                $(".msgBox").html("");
            })
            $("#lbSendtoUser").click(function () {
                $("#lbSendtoUser").text("")
            });
        })

        function selUser(key, name) {
            var arr = [];
            var arr1 = [];
            var tolist = $("#lbSendtoUser").text();
            var toconnid = $("#lbSendtoUser").attr("connid");
            if (tolist) {
                arr = tolist.split(',');
                arr1 = toconnid.split(',');
            }
            if ($.inArray(key, arr1) == -1) {
                arr.push(name);
                arr1.push(key);
            }
            else {
                arr.splice(arr.indexOf(name), 1);
                arr1.splice(arr1.indexOf(key), 1);
            }
            $("#lbSendtoUser").text(arr.join(','));
            $("#lbSendtoUser").attr("connid", arr1.join(','));
        }
    </script>
    <style>
        .msgBox {
            height: 380px;
            border: solid 1px #0094ff;
            overflow: auto;
        }
        .msgOper {
        }
        .txtMsg {
            width: 95%;
            height: 100px;
        }
        .user {
            color: forestgreen;
        }
        .sendto {
            color: #0094ff;
        }
        .time {
            color: fuchsia; 
        }
        .divLeft {
            float: left;
            width: 70%;
        }
        .divMid {
            float: left;
            width: 1%;
        }
        .divRight {
            float: left;
            width: 29%;
        }        
        .spliter {
            height: 500px;
        }
        .userList {
            height: 500px;
            border: solid 1px #0094ff;
            overflow: auto;            
        }
        .userItem {
            height: 40px;
            line-height: 40px;
            vertical-align: middle;
            font-size: x-large;
            color: #0094ff;
            background-color: #f5f5f5;
            border-bottom: 1px solid #ff0000;
            cursor: pointer;
        }
        .userItem a{
            width: 100%;
            display: block;
        }
        .lbTo {
            margin-left: 50%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="divLeft">
                <div class="msgBox" id="msgBox">    
                </div>
                <div class="msgOper">
                    <div>
                        <span>用户名:</span>
                        <asp:Label ID="lbUsername" runat="server" Text=""></asp:Label>
                        <span class="lbTo">发送给:</span>
                        <span id="lbSendtoUser"></span>
                    </div>
                    <div>
                        <textarea class="txtMsg" id="txtMsg" placeholder="输入内容..."></textarea>
                    </div>
                    <div>
                        <input type="button" class="btnSend" id="btnSend" value="发    送"/>
                        <input type="button" class="btnClear" id="btnClear" value="清    屏"/>
                        <asp:Button ID="btnQuit" runat="server" Text="退    出" OnClick="btnQuit_Click" />
                    </div>
                </div>
            </div>
            <div class="divMid">
                <div class="spliter"></div>
            </div>
            <div class="divRight">
                <div class="userList">
                    <ol id="olUserlist"></ol>
                </div>
            </div>
        </div>
    </form>
</body>
</html>

4.效果图

ASP.NET+SignalR聊天室
ASP.NET+SignalR聊天室
ASP.NET+SignalR聊天室

email:654088909@qq.com

原文出处:博客园【LiveCoding】

原文链接:https://www.cnblogs.com/LiveCoding/p/13304130.html

本文观点不代表Dotnet9立场,转载请联系原作者。

发表评论

登录后才能评论