asp实现在线人数的总计,每登录一个,在线人数就加一,访问量也是,不过访问量最后要保存起来,下次登录读取且加一,就是访问量实时更新。
1.首先在项目中右键点击添加,选择新建项,找到全局应用程序类,如果你找到这个类,看看你项目里面是否已经存在了,如果存在项目里你是找不到的。
2.在全局类中写入以下代码,代码很简单,我也没怎么写注释
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace OnlineExam
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Application["zxrs"] = 0;//在线人数
System.IO.FileStream fs = System.IO.File.Open(
Server.MapPath("Count.txt"), System.IO.FileMode.OpenOrCreate);
System.IO.StreamReader sr = new System.IO.StreamReader(fs);
Application["AllUsers"] = Convert.ToInt32(sr.ReadLine());
sr.Close();
fs.Close();
}
protected void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["zxrs"] = Convert.ToInt32(Application["zxrs"]) + 1;//在线人数总计
Application["AllUsers"] = Convert.ToInt32(Application["AllUsers"]) + 1;//访问人数总计
System.IO.FileStream fs = System.IO.File.Open(
Server.MapPath("Count.txt"), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);//生成count文件保存更新访问量
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
sw.WriteLine(Application["AllUsers"]);
sw.Close();
fs.Close();
Application.UnLock();
}
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)
{
Application["zxrs"] = Convert.ToInt32(Application["zxrs"]) - 1;
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
3.最后在你想显示的页面后台读取一般是主页面或者母版页下(我前台aspx页面放了两个Label标签 lbl_Text,lbl_count分别为它们的id)
lbl.Text += " 在线人数: " + Application["zxrs"].ToString();
lbl_count.Text += " 系统访问量: " + Application["AllUsers"].ToString();
4.最后可以测试一下,两个浏览器登录你的系统就可以看到可以实现了。