实现在线人数统计

本文介绍了如何使用Global.asax文件中的Application和Session事件来管理ASP.NET应用中的在线人数统计。通过设置Session的超时时间,并在Session启动和结束时更新Application变量来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 在解决方案资源管理器中添加新项,Global.asax,其中代码如下:

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
Application["count"] = 0;
}

void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码

}

void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码

}

void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
Session.Timeout = 1;//超时时间
Application.Lock();
Application["count"] = (int)Application["count"]+1;
Application.UnLock();
}

void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
//Session.Abandon();
Application.Lock();
Application["count"] = (int)Application["count"] - 1;
Application.Lock();
}

</script>
在首页面写入以下:

protected void Page_Load(object sender, EventArgs e)
{
Response.Write("当前在线人数:"+Application["count"].ToString());

}

这种方法不是很准确,因为它有一个超时时间,这里设置的是一分钟,也就是说一分钟后才会将对话关闭,触发Session_End事件,而VS2005中,一般默认是20分钟,可以通过设置Session.Timeout = 1;//超时时间来改变,最小是一分钟.

using System; using System.Data; using System.Text; namespace ZKXP.BLL { /// /// OnLine 的摘要说明。 /// public class OnLine { private string USERNAME; private int OFFLINEDIFF; private int REMOVEDIFF; public OnLine() { //直接在这里设定、或从配置文件中读取配置参数 ///存放用户名的Session名 USERNAME = "UserName"; ///多少分钟不活动的用户从在线列表中删除 OFFLINEDIFF = 5; ///多少秒执行一次删除不活动用户 REMOVEDIFF = 30; 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(); //数据表中是否有我的记录 DataRow drFind = dtOnline.Rows.Find(sessionId); if(drFind != null) { //有;更新我的状态 Info.Write("更新"); drFind["LastActiveTime"] = DateTime.Now; drFind["UserWhere"] = this.AtWhere; //用户由访客状态变为了登陆会员、或反之 if(Extend.GetSession(USERNAME) != null) { drFind["VisitorName"] = Extend.GetSession(USERNAME); drFind["VisitorLevel"] = Extend.GetSession("UserLevel"); } else { drFind["VisitorName"] = "vst"; drFind["VisitorLevel"] = -1; } } else { //无;加入关于我的在线信息 Info.Write("插入"); DataRow drNew = dtOnline.NewRow(); drNew["SessionID"] = sessionId; drNew["VisitorName"] = "vst"; drNew["VisitorLevel"] = -1; drNew["LastActiveTime"] = DateTime.Now; drNew["LoginTime"] = DateTime.Now; drNew["VisitorIP"] = Extend.GetRealIP();; 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 OFFLINEDIFF) { dtOnline.Rows.Remove(drDel); } } //我删完了,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(); } private string GetApplication(string apcname) { return System.Web.HttpContext.Current.Application[apcname].ToString(); } public void SetApplication(string apcname, string apcvalue) { System.Web.HttpContext.Current.Application[apcname] = apcvalue; } /// /// 返回用户当前位置 /// 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() ; } } /// /// 创建表 /// 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"; } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值