Asp.net----SignalR 及時推送

一.簡介:來自微軟的介紹

微軟文章地址:https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr

二:SignalR  的使用

測試環境:VS2015

在這裏 我用 SignalR做了一個小的聊天室demo  簡單易懂  幫助大家理解  效果截圖

首先:我們新建一個.net  MVC的程序  打開VS

新建MVC  我這裏是用的  VS2015   鼠標右鍵點擊項目名稱  點擊管理NuGet程序包   瀏覽 搜索SignalR

點擊安裝

如果VS版本較低的話,可能會出現安裝錯誤,那可能是因爲jQuery版本較低  需要卸載之前的版本  再安裝SiglnaR

注意:版本低的Vs不會自動自動生成Starup.cs類

廢話不多說了,直接貼代碼:

第一步:創建Startup.cs類(版本高的VS會自動創建MVC時生成)

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

第二步:創建一個集線器類,用來裝所有需要使用的方法.

繼承Hub類,並且引入命名空間:

using Microsoft.AspNet.SignalR;
using System.Web.Script.Serialization;

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

namespace SignalRDemo
{
    /// <summary>
    /// TalkHub類集線器類
    /// </summary>
    public class TalkPeople: Hub//繼承Hub
    {

        //使用SignalR中 一定要記住 
        //前臺即client調用後臺方法
        //後臺即server調用前臺方法
        //要弄清楚 不然很容易迷糊
        public static List<UserInfos> list = new List<UserInfos>();//用戶集合
        /// <summary>
        /// 通知上線
        /// </summary>
        /// <param name="name"></param>
        public void OnLine(string name)
        {
            //存放客戶信息
            UserInfos s = new UserInfos() { Id =Context.ConnectionId, name = name };
            list.Add(s);
            string json = new JavaScriptSerializer().Serialize(list);
            Clients.All.UserOnlie(s.Id, s.name, json);//調用前臺方法UserOnlie()返回用戶信息
            //注:UserOnlie();不是後臺方法 而是前臺聲明的方法 
        }



        /// <summary>
        /// 通知下線
        /// </summary>
        /// <param name="stopCalled"></param>
        /// <returns></returns>
        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            UserInfos u = list.Where(s => s.Id == Context.ConnectionId).FirstOrDefault();
            list.Remove(u);
            Clients.Others.UserDrop(u.Id, u.name,list.Count);
            return base.OnDisconnected(stopCalled);
        }

        /// <summary>
        /// 消息羣發(通知所有人)
        /// </summary>
        public void SendMsgToAll(string name, string msg)
        {
            string time = DateTime.Now.ToLocalTime().ToString();

            Clients.All.GetAllMsg(name, msg, time);
        }

        /// <summary>
        /// 私聊
        /// </summary>
        public void SendMsgToSomeBody(string name, string uid, string msg)
        {
            string[] array = new string[] { };
            string time = DateTime.Now.ToLocalTime().ToString();
            uid = uid.Substring(0,uid.Length-1);
            array = uid.Split(',').ToArray();

            foreach (var item in array)
            {
                Clients.Client(item).GetSomeBodyMsg(name, msg, time);
            }
        }
    }
}

實體類:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SignalRDemo
{
    public class UserInfos
    {
        public string Id { get; set; }
        public string name { get; set; }
    }
}

第三步:前臺HTML佈局:


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    @*注意:一定要引入signalR.js並且手寫  <script src="/signalr/hubs"></script>*@
    <script src="~/Scripts/jquery.signalR-2.4.0.js"></script>
    <script src="/signalr/hubs"></script>
    <style>
       
        #chat_div{
         height: 733px;
        border: 1px solid gray;
        width: 833px;
        }
        #list_user{
            float:right;
            width:30%;
            height:100%;
             
        }
        .list_user_title{
           float: left;
            height: 5%;
            width: 100%;
          
            text-align: center;
            line-height: 38px;
            font-size: 18px;
            font-weight: 1000;
        }
        .list_user_online{
            float: left;
            height: 85%;
            width: 95%;
            border: 1px solid gray;
            overflow: auto;

        }
        .nock{
              border-radius: 6%;
            list-style-type: none;
            height: 25px;
            width: 92%;
            background-color: gray;
            margin-top: 9px;
            margin-left: 3.5%;
            text-align: center;
            line-height: 25px;
            cursor: pointer;
            color:white;
        }
         .isck{
              border-radius: 6%;
            list-style-type: none;
            height: 25px;
            width: 92%;
            background-color:#88bda9;
            margin-top: 9px;
            margin-left: 3.5%;
            text-align: center;
            line-height: 25px;
            cursor: pointer;
            color:white;
        }
        .list_user_content{
             float: left;
              height: 66%;
             width: 69%;
            border:1px solid gray;
             overflow: auto;
        }
        .list_user_msg{
            float: left;
            height: 32%;
            width: 69%;
          
            margin-top: 1%; 
        }
        .list_user_msg_text textarea{
                float: left;
                height: 164px;
                width: 100%;
              
                margin-top: 1%;
        }
        .list_user_msg_button{
            float:left;
            height: 46px;
            width: 99%;
            margin-top: 3%;
            margin-left: 74%;
        }
        #tatol_div{
            float:left;
            margin-left:20%;
              margin-top:7%;
        }
        .content_name{
            color:#556bee;
        }
        .content_time{
            color:green;
        }
        .content_msg{
            font-size:16px;
            color:gray;
            font-family:'Microsoft PhagsPa';
        }
          .content_msg_per{
            font-size:16px;
            color:red;
            font-family:'Microsoft PhagsPa';
        }
        .msg_div{
            margin-top:27px;
        }
    </style>
</head>
<body>

    <div id="tatol_div">
        <div id="chat_div">

            <div id="list_user">
                @*標題*@
                <div class="list_user_title">
                    大佬聊天室(<span id="num"></span>)
                </div>

                @*右側用戶List*@
                <div class="list_user_online">
                    <ul>
                        
                    </ul>
                </div>
            </div>

            @*聊天內容*@
            <div class="list_user_content">
               
            </div>
            @*發送消息界面*@
            <div class="list_user_msg">

                <div class="list_user_msg_text">
                    <textarea id="msg_text"></textarea>
                </div>
                @*按鈕*@
                <div class="list_user_msg_button">
                    <button id="btn_send" >發送</button>
                    <button id="btn_clear">清空</button>
                </div>
            </div>
        </div>
    </div>
    <script>
        var username = "";
        $(function () {
            //連接服務器
            var chat = $.connection.talkPeople;//注意:TalkHub首字母一定要小寫  方法也是一樣
            //第一個參數是提示文字,第二個參數是文本框中默認的內容
             username = prompt("請輸入暱稱!", "");
                if (username==""||username==null) {
                    alert("請輸入暱稱!");
                    return;
                }
                //啓動服務器
                $.connection.hub.start().done(function ()
                {
                    chat.server.onLine(username);//調用服務端方法 OnLine()通知有人上線了;
                });
            //客戶端通知方法 有人上線了
            chat.client.UserOnlie = function (id, name, jsonStr) {
                alert(name+'上線啦! ');
                var strData = eval(jsonStr);
                if (strData.length > 0)
                {
                    var strhtml = "";
                    for (var i = 0; i < strData.length; i++) {
                        strhtml += '<li class="nock" id=' + strData[i].Id + '>' + strData[i].name + '</li>';
                    }
                    $("#num").html("在線人數:"+strData.length);
                    $(".list_user_online ul").html(strhtml);//追加客戶
                    $(".nock").click(function () {
                        if ($(this).hasClass("nock")) {
                            $(this).removeClass("nock");
                            $(this).addClass("isck");
                        } else {
                            $(this).removeClass("isck");
                            $(this).addClass("nock");
                        }
                    });
                }
            };
            //發送消息
            $("#btn_send").click(function ()
            {
                var msg = $("#msg_text").val();//獲取消息內容
                var userid = "";//獲取發消息給誰的userid(支持同時發送消息給幾個人) 若爲空則羣發 
                $(".isck").each(function(){
                    userid += $(this).attr("id")+',';
                });//拼接選中的值
                if (userid!="") {
                    if (msg == "") {
                        layer.msg("內容不能爲空!", { icon: 2, time: 3000 });
                    } else {
                        //私聊
                        chat.server.sendMsgToSomeBody(username, userid, msg);
                    }
                } else {
                    //羣發
                    chat.server.sendMsgToAll(username, msg);
                }
            });



            //接收所有公共的消息
            chat.client.GetAllMsg = function (name, msg, time) {
                var msgstow = '<span class="content_time">' + time + '</span><br/>&emsp;&emsp;&emsp;&emsp;<span class="content_msg">' + msg + '</span></div>';
                var msgs = '<div class="msg_div">';
                var fina='';
                if (name == username) {
                    fina='<span  style="color:red;">' + name + ':</span>';
                } else {
                    fina='<span class="content_name">' + name + ':</span>';
                }
                fina=msgs+fina+msgstow;
                $(".list_user_content").append(fina);
            }

            //接收私聊信息
            chat.client.getSomeBodyMsg = function (name, msg, time) {
                $(".list_user_content").append('<div class="msg_div"><span class="content_name">' + name + '對我私聊:</span><span class="content_time">' + time + '</span><br/>&emsp;&emsp;&emsp;&emsp;<span class="content_msg_per">' + msg + '</span></div>');
            }
            //下線通知
            chat.client.UserDrop = function (id, username,count) {
                alert(username + '下線啦!');
                $("#num").html("在線人數:" + count);
                $("#" + id + "").remove();
            }
        });
    </script>
</body>
</html>

註釋都在其中 不懂的可以留言問我.

原文地址:

https://www.zddblog.top/Home/Detail?art_id=NDM=

源碼下載:

https://download.csdn.net/download/bigbossc/10925892

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章