SignalR 初学 与数据库交互,实时刷新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25027593/article/details/81870927

代码只是我的理解,可能有错误,仅供新手参考,不保证正确性。

逻辑梳理:数据库数据如发生变化,通过dependency_OnChange事件监听到,监听之后执行Show()方法,给所有连接SignalR的客户端发送通知(displayDatas),页面收到通知,执行getdata()方法,重新获取数据。

1.新建项目

2.右击项目,管理NuGet程序包,搜索SignalR  下载第一个

3.添加hub.js

(function ($, window, undefined) {
    "use strict";

    if (typeof ($.signalR) !== "function") {
        throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js.");
    }

    var signalR = $.signalR;

    function makeProxyCallback(hub, callback) {
        return function () {
            callback.apply(hub, $.makeArray(arguments));
        };
    }

    function registerHubProxies(instance, shouldSubscribe) {
        var key, hub, memberKey, memberValue, subscriptionMethod;

        for (key in instance) {
            if (instance.hasOwnProperty(key)) {
                hub = instance[key];

                if (!(hub.hubName)) {
                    continue;
                }

                if (shouldSubscribe) {
                    subscriptionMethod = hub.on;
                } else {
                    subscriptionMethod = hub.off;
                }

                for (memberKey in hub.client) {
                    if (hub.client.hasOwnProperty(memberKey)) {
                        memberValue = hub.client[memberKey];

                        if (!$.isFunction(memberValue)) {
                            continue;
                        }
                        subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));
                    }
                }
            }
        }
    }

    $.hubConnection.prototype.createHubProxies = function () {
        var proxies = {};
        this.starting(function () {
            registerHubProxies(proxies, true);

            this._registerSubscribedHubs();
        }).disconnected(function () {
            registerHubProxies(proxies, false);
        });

        proxies['chatHub'] = this.createHubProxy('chatHub');
        proxies['chatHub'].client = {
        };
        proxies['chatHub'].server = {
        };

        return proxies;
    };

    signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
    $.extend(signalR, signalR.hub.createHubProxies());

}(window.jQuery, window));

4.添加一个html,添加 jquery-3.1.1.min.js、jquery.signalR-2.3.0.js、hub.js,第一个为jq下载最新即可,第二个为步骤2下载的SignalR里面,第三个为上面贴的hub.js

5.添加全局文件Global.asax

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace WebSCADA
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            //开始数据库的更新监听
            SqlDependency.Start(ConfigurationManager.ConnectionStrings["Entities"].ConnectionString);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            //停止数据库的更新监听
            SqlDependency.Stop(ConfigurationManager.ConnectionStrings["Entities"].ConnectionString);
        }
    }
}

6.添加类Startup.cs

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

namespace WebSCADA
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

7.添加ChatHub类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using WebSCADA.admin.net.DB;
using System.Web.Script.Serialization;
using Microsoft.AspNet.SignalR.Hubs;

namespace WebSCADA
{
    public class ChatHub : Hub
    {
        public static void Show() {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.displayDatas();//注意此处displayDatas
        }
    }
}

8.添加一般处理程序SignalRGetData.ashx  后面获取数据和数据库监控都写在此

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using WebSCADA.admin.net.DB;

namespace WebSCADA.admin.net
{
    /// <summary>
    /// SignalRGetData 的摘要说明
    /// </summary>
    public class SignalRGetData : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            List<Device> list = GetData();
            context.Response.Write(new JavaScriptSerializer().Serialize(list));
        }
       
        ///获取数据
        public List<Device> GetData()
        {
            using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Entities"].ConnectionString))
            {
                sqlConnection.Open();
                using (SqlCommand sqlcommand = new SqlCommand(@"SELECT [deviceid],[orgid],[orgname],[devname],[Address],[IndexOfType],[Description],[CurValue],[RecvTime] FROM [dbo].[Device]", sqlConnection))
                {
                    sqlcommand.Notification = null;
                    SqlDependency dependency = new SqlDependency(sqlcommand);
                    
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (sqlConnection.State == ConnectionState.Closed)
                    {
                        sqlConnection.Close();
                    }
                    using (var reader = sqlcommand.ExecuteReader())
                        return reader.Cast<IDataRecord>().Select(oo => new Device()
                        {
                            deviceid = oo["deviceid"].ToString(),
                            orgid = oo["orgid"].ToString(),
                            orgname = oo["orgname"].ToString(),
                            devname = oo["devname"].ToString(),
                            Address = oo["Address"].ToString(),
                            IndexOfType = oo["IndexOfType"].ToString(),
                            Description = oo["Description"].ToString(),
                            CurValue = oo["CurValue"].ToString(),
                            RecvTime = Convert.ToDateTime(oo["RecvTime"]),
                        }).ToList();
                }
            }
        }
        
        ///监测数据库变化
        ///如果数据库数据发生变化,则进入该方法,此方法会跳转到ChatHub.cs Show()方法
        ///Show()方法会给所有客户端发送通知 displayDatas 
        ///页面监测着displayDatas 所以页面会收到数据库变化通知,即可重新获取数据
        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            ChatHub.Show();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

9.html页面添加SignalR连接代码如下:

var proxy = $.connection.chatHub;
//此处displayDatas即ChatHub类Show方法里面的
proxy.client.displayDatas = function () {
       //获取数据
       getdata();
}
$.connection.hub.start();
//获取数据
getdata();

function getdata(){
     $.ajax({
            cache: false,
            type: "POST",
            url: "SignalRGetData.ashx",
            data: {},
            async: false,
            error: function (request) {
                console.log(request);
            },
            success: function (data) {
                //重新刷新页面
            }
        });
}

猜你喜欢

转载自blog.csdn.net/qq_25027593/article/details/81870927