首页 > 代码库 > 网站档机监控

网站档机监控

<%@ Page Language="C#" AutoEventWireup="true" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server">    protected void Page_Load(object sender, EventArgs e)    {        Response.Expires = -1;        var m = Request["m"];        if (string.Compare(m, "GetData", true) == 0)        {            GetData();            Response.End();        }        sqlCmd.InnerText = sql;    }    private List<ElecStatus> ElecScaleList = new List<ElecStatus>()        {            new ElecStatus(){GroupId="192.168.77.1",Status=-1},            new ElecStatus(){GroupId="192.168.77.2",Status=-1},            new ElecStatus(){GroupId="192.168.77.3",Status=-1},            new ElecStatus(){GroupId="192.168.77.4",Status=-1},            new ElecStatus(){GroupId="192.168.77.5",Status=-1},            new ElecStatus(){GroupId="192.168.77.6",Status=-1}        };    private void GetData()    {        var list = Query();        var expScaleList = ElecScaleList.Except(list);        var retList = list.Union(expScaleList).OrderBy(ent => ent.GroupId);         //专发器访问状态        if (HealthMoniter.Running)        {            foreach (var webSite in HealthMoniter.WebSiteList)            {                var it=retList.FirstOrDefault(ent => ent.GroupId == webSite.Url);                if (it != null)                {                    it.RepeaterStatus = webSite.Status;                }            }        }        else        {           var q= ElecScaleList.Select(ent => new WebSiteStatus() { Url = ent.GroupId, Status = -1, LastCheckTime = DateTime.Now });           HealthMoniter.StartMonitor(q.ToList());        }                var sb = new StringBuilder();        using (var writer = new HtmlTextWriter(new System.IO.StringWriter(sb)))        {            Repeater1.DataSource = retList;            Repeater1.DataBind();            Repeater1.RenderControl(writer);            writer.Flush();        }        Response.Write("监控数:" + HealthMoniter.WebSiteList.Count +"<br/>");        Response.Write("获取时间:" + DateTime.Now + "<br/>" + sb.ToString());    }    private static string ConnStr = @"data source=192.168.1.91;initial catalog=JL_MFG;persist security info=True;user id=sa;password=admin;multipleactiveresultsets=True;";    private String sql = @"select * from ElecScale        where RecId in        (            select max(RecId) from ElecScale            where AddTime>=  dateAdd(ss,-5,getdate())            group by GroupId        ) ";    private List<ElecStatus> Query()    {        #region cmd        #endregion        var list = new List<ElecStatus>();        using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(ConnStr))        {            using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, conn))            {                conn.Open();                using (var reader = cmd.ExecuteReader())                {                    while (reader.Read())                    {                        var ent = new ElecStatus();                        ent.GroupId = reader["GroupId"].ToString();                        ent.Legend = reader["Legend"].ToString();                        ent.V = reader["V"].ToString();                        ent.Status = 0;                        list.Add(ent);                    }                }            }        }        return list;    }    public class ElecStatus    {        public String GroupId { get; set; }        public String V { get; set; }        public String Legend { get; set; }        /// <summary>        /// 0:正常1:异常        /// </summary>        public int Status { get; set; }        public DateTime AddTime { get; set; }        public int? RepeaterStatus { get; set; }        public override bool Equals(object obj)        {            if (obj == null) return false;            var ent = (obj as ElecStatus);            return this.GroupId.Equals(ent.GroupId);        }        public override int GetHashCode()        {            return GroupId.GetHashCode();        }    }    public class WebSiteStatus    {        public String Url { get; set; }        public int? Status { get; set; }        public DateTime? LastCheckTime { get; set; }    }    public class HealthMoniter : IDisposable    {        private static readonly HealthMoniter _Instance = new HealthMoniter();        public static void StartMonitor(List<WebSiteStatus> list)        {            _Instance.WebSites.Clear();            _Instance.WebSites.AddRange(list);            _Instance.Start();        }        public static void StopMonitor()        {            _Instance.Stop();        }        public static List<WebSiteStatus> WebSiteList        {            get            {                return _Instance.WebSites;            }        }        public static bool Running        {            get            {                return _Instance.IsRunning;            }        }        private bool IsRunning { get;  set; }        private bool IsEnabled { get; set; }        private List<WebSiteStatus> WebSites { get; set; }        private HealthMoniter()        {            IsRunning = false;            IsEnabled = false;            this.WebSites = new List<WebSiteStatus>();        }        public void Start()        {            lock (this)            {                if (IsRunning) return;                IsEnabled = true;                System.Threading.Tasks.Task.Factory.StartNew(_Start);            }        }        private void _Start()        {            IsRunning = true;            while (IsEnabled)            {                var taskList = new List<System.Threading.Tasks.Task>();                foreach (var it in WebSites)                {                    var website = it;                    System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() =>                    {                        try                        {                            var rnd = "/login.cgi?" + DateTime.Now.Ticks;                            System.Net.WebClient wc = new System.Net.WebClient();                            var str = wc.DownloadString("http://" + website.Url + rnd);                            Console.WriteLine("http://" + website.Url + rnd);                            if (!string.IsNullOrWhiteSpace(str))                            {                                if (str.IndexOf("www.usr.cn") > 0)                                {                                    website.Status = 0;                                    website.LastCheckTime = DateTime.Now;                                }                            }                        }                        catch (Exception)                        {                            website.LastCheckTime = DateTime.Now;                            website.Status = -4;                        }                    });                    taskList.Add(task);                    task.Start();                }                System.Threading.Tasks.Task.WaitAll(taskList.ToArray());                System.Threading.Thread.Sleep(1000 * 5);            }            IsRunning = false;        }        public void Stop()        {            IsEnabled = false;        }        private bool disposed = false;        /// <summary>        /// Performs application-defined tasks associated with freeing,         /// releasing, or resetting unmanaged resources.        /// </summary>        public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        /// <summary>        /// Releases unmanaged and - optionally - managed resources        /// </summary>        /// <param name="disposing"><c>true</c> to release both managed         /// and unmanaged resources; <c>false</c>         /// to release only unmanaged resources.        /// </param>        protected virtual void Dispose(bool disposing)        {            if (!this.disposed)            {                if (disposing)                {                    try                    {                        Stop();                    }                    catch                    {                    }                }                disposed = true;            }        }    }</script><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>电子称状态监控</title>    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/jquery-1.4.1-vsdoc.js"></script>    <script type="text/javascript" src=http://www.mamicode.com/"Scripts/jquery.timers-1.1.2.js"></script>    <script type="text/javascript">        $(document).ready(function () {            setInterval(queryScale, 1000);        });        function queryScale() {            var url = "/ESM.aspx";            $("#panelShow").load(url, { m: "GetData", rnd: new Date().getTime() });        }           </script>    <style type="text/css">        body        {            font-size: 12px;        }    </style></head><body>    <form id="form1" runat="server">    <div id="panelShow">        <asp:Repeater ID="Repeater1" runat="server">            <HeaderTemplate>                <table style="width: 100%; background-color: #eeeeee" cellspacing="2">                    <tr style="background-color: White; font-weight: bold">                        <td style="width: 6%">                            编号                        </td>                        <td style="width: 20%">                            读数                        </td>                        <td style="width: 10%; text-align: center">                            状态                        </td>                        <td style="text-align: center">                            转发器状态&nbsp;                        </td>                    </tr>            </HeaderTemplate>            <ItemTemplate>                <tr style="background-color: White;">                    <td>                        <%#Eval("GroupId").ToString().Substring(11) %>                    </td>                    <td>                        <%#Eval("V") %>                    </td>                    <td style="text-align: center">                        <%# (int)Eval("Status") == 0 ? "<font color=‘green‘>正常</font>" : "<font color=‘red‘>异常</font>"%>                    </td>                    <td  style="text-align: center">                      <a href=http://www.mamicode.com/http://<%#Eval("GroupId") %> target="_blank"><%# (int)Eval("RepeaterStatus") == 0 ? "<font color=‘green‘>正常</font>" : "<font color=‘red‘>异常</font>"%></a>                     </td>                </tr>            </ItemTemplate>            <FooterTemplate>                </table>            </FooterTemplate>        </asp:Repeater>    </div>    <hr />    <strong>使用下列语句轮询数据</strong><br />    <textarea id="sqlCmd" runat="server" style="width: 100%" name="S1" rows="9"></textarea>    </form></body></html>
View Code

定时访问网站检测页

网站档机监控