c# 统计在线会员人数

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;

/// <summary>
///onlineCount 的摘要说明
/// </summary>
public class onlineCount
{
    private string USERNAME;
    private int OFFLINEDIFF;
    private int REMOVEDIFF;

    public onlineCount()
    {
        //直接在这里设定、或从配置文件中读取配置参数
        ///存放用户名的Session名
        USERNAME = HttpContext.Current.Session["username"].ToString();
        ///多少分钟不活动的用户从在线列表中删除
        ///u
        OFFLINEDIFF = 5;
        ///多少秒执行一次删除不活动用户
        REMOVEDIFF = 10;

        if (System.Web.HttpContext.Current.Application["OnlineTalbe"] == null)
        {
            this.CashTableInit();
        }
    }
    public void CheckOnline()
    {
        //从Application获取数据表、获取SessionID
        DataTable dtOnline;
        dtOnline = (DataTable)System.Web.HttpContext.Current.Application["OnlineTalbe"];
        string sessionId = System.Web.HttpContext.Current.Session.SessionID.ToString();
        //System.Web.HttpContext.Current.Response.Write(sessionId);

        //数据表中是否有我的记录
        DataRow drFind = dtOnline.Rows.Find(sessionId);
        if (drFind != null)
        {
            //有;更新我的状态
            drFind["LastActiveTime"] = DateTime.Now;
            drFind["UserWhere"] = this.AtWhere;
            //用户由访客状态变为了登陆会员、或反之
            drFind["VisitorName"] = USERNAME;
            drFind["VisitorLevel"] = 1;
        }
        else
        {
            //无;加入关于我的在线信息
            DataRow drNew = dtOnline.NewRow();
            drNew["SessionID"] = sessionId;
            drNew["VisitorName"] = USERNAME;
            drNew["VisitorLevel"] = 1;
            drNew["LastActiveTime"] = DateTime.Now;
            drNew["LoginTime"] = DateTime.Now;
            drNew["VisitorIP"] = System.Web.HttpContext.Current.Request.UserHostAddress;
            drNew["UserWhere"] = this.AtWhere;

            dtOnline.Rows.Add(drNew);
        }
        //如果没有人正在执行删除且离上次删除的时间间隔超过设定值

        TimeSpan tsRemove = DateTime.Now - Convert.ToDateTime(GetApplication("LastRemove"));
        if (tsRemove.Seconds > REMOVEDIFF && this.GetApplication("Removing").ToString() == "n")
        {
            //锁定,我正在删除过期用户
            System.Web.HttpContext.Current.Application.Lock();
            SetApplication("Removing", "y");
            System.Web.HttpContext.Current.Application.UnLock();
            //不知道Rows.Count是否随循环减少,如果是效率就大于foreach且这里不能使用foreach
            for (int i = 0; i < dtOnline.Rows.Count; i++)
            {
                DataRow drDel = dtOnline.Rows[i];
                TimeSpan ts = DateTime.Now - Convert.ToDateTime(drDel["LastActiveTime"]);
                if (ts.Minutes > OFFLINEDIFF)
                {
                    dtOnline.Rows.Remove(drDel);
                    System.Web.HttpContext.Current.Response.Write("好累");
                }
            }


            System.Web.HttpContext.Current.Application.Lock();
            SetApplication("Removing", "n");
            SetApplication("LastRemove", DateTime.Now.ToString());
            System.Web.HttpContext.Current.Application.UnLock();
        }

        //把被我揉腻完了的数据表放回Application
        dtOnline.AcceptChanges();
        System.Web.HttpContext.Current.Application.Lock();
        System.Web.HttpContext.Current.Application["DataTalbeOnline"] = dtOnline;
        System.Web.HttpContext.Current.Application.UnLock();
    }
    //根据apcname得到对应的值
    private string GetApplication(string apcname)
    {
        return System.Web.HttpContext.Current.Application[apcname].ToString();
    }
    //给Application赋值
    public void SetApplication(string apcname, string apcvalue)
    {

        System.Web.HttpContext.Current.Application[apcname] = apcvalue;

    }
    /// <summary>
    /// 返回用户当前位置
    /// </summary>
    private string AtWhere
    {
        get
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(System.Web.HttpContext.Current.Request.ServerVariables["url"]);
            if (System.Web.HttpContext.Current.Request.ServerVariables["QUERY_STRING"] != String.Empty)
            {
                sb.Append("?");
                sb.Append(System.Web.HttpContext.Current.Request.ServerVariables["QUERY_STRING"]);
            }
            return sb.ToString();
        }
    }
    /// <summary>
    /// 创建表
    /// </summary>
    public void CashTableInit()
    {
        DataTable dt = new DataTable("OnlineTalbe"); //创建临时表
        dt.Columns.Add("SessionID", typeof(string));
        dt.Columns.Add("VisitorName", typeof(string));
        dt.Columns.Add("VisitorLevel", typeof(int));
        dt.Columns.Add("LastActiveTime", typeof(DateTime));
        dt.Columns.Add("LoginTime", typeof(DateTime));
        dt.Columns.Add("VisitorIP", typeof(string));
        dt.Columns.Add("UserWhere", typeof(string));
        dt.Columns["SessionID"].Unique = true;
        dt.PrimaryKey = new DataColumn[] { dt.Columns["SessionID"] };

        System.Web.HttpContext.Current.Application["OnlineTalbe"] = dt;
        System.Web.HttpContext.Current.Application["LastRemove"] = DateTime.Now.ToString();
        System.Web.HttpContext.Current.Application["Removing"] = "n";
    }
}

 

在要统计的每个用户页面上加

 

 protected void Page_Load(object sender, EventArgs e)
    {
        
        //测试在线统计
        onlineCount oc = new onlineCount();
        oc.CheckOnline();

  }

 

在要显示统计人数的页面上加

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Application["OnlineTalbe"] != null)
            {

                bindData();
               
            }


        }


    }

    void bindData()
    {
        if (Application["OnlineTalbe"] != null)
        {
            DataTable dt = (DataTable)Application["OnlineTalbe"];
            DataList1.DataSource = dt;
            DataList1.DataBind();

            int totalrecord = dt.Rows.Count;
            AspNetPager1.RecordCount = totalrecord;

            dt.Dispose();
        }

    }

    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {

        bindData();

    }

 

 

你可能感兴趣的:(C#)