Asp.Net 网站访问人数及在线人数

很久没有做Asp.Net的项目,突然有一个项目需要网站访问人数及在线人数的统计,特意做一个这样的功能模块。

在Global.asax文件中添加以下代码

<%@ Application Language="C#" %>
<script runat="server">
string sLogFile = AppDomain.CurrentDomain.BaseDirectory + "VisitedLog.txt";
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
// Code that runs on application startup
//刚启动,为了防止服务器意外死机重启等因素,需要从记录文件中读取数目
if (!System.IO.File.Exists(sLogFile))
{
System.IO.FileStream fsnew = System.IO.File.Create(sLogFile);
fsnew.Close();
}
string[] lines = System.IO.File.ReadAllLines(sLogFile);
double iTotalCount = 0;
int iOnline = 0;
if (lines != null && lines.Length > 0)
{
Double.TryParse(lines[lines.Length - 1].ToString(), out iTotalCount);
}
Application["TotalCount"] = iTotalCount;
Application["Online"] = iOnline;
}
void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
System.IO.StreamWriter rw = System.IO.File.CreateText(sLogFile);
rw.WriteLine(Application["TotalCount"]);
//rw.WriteLine();
rw.Flush();
rw.Close();
}
void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
// Code that runs when a new session is started
Session.Timeout = 10;
Application.Lock();
Application["TotalCount"] = System.Convert.ToDouble(Application["TotalCount"]) + 1;
Application["Online"] = System.Convert.ToInt32(Application["Online"]) + 1;
Application.UnLock();
if (Convert.ToInt32(Application["TotalCount"]) % 50 == 0)
{
System.IO.StreamWriter rw = System.IO.File.CreateText(sLogFile);
rw.WriteLine(Application["TotalCount"]);
//rw.WriteLine();
rw.Flush();
rw.Close();
}
}
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
Application.Lock();
Application["Online"] = System.Convert.ToInt32(Application["Online"]) - 1;
Application.UnLock();
}
</script>