统计在线人数

<%@ Import Namespace="System.Data"%>
void Application_Start(object sender, EventArgs e) 
    {
       //在应用程序启动时运行的代码,网站启动时即出发此事件
        try
        {

            DataTable userTable = new DataTable();
            userTable.Columns.Add("SessionID");
            userTable.Columns.Add("UserIP");
            userTable.Columns.Add("Browser");
            userTable.Columns.Add("OSName");

            userTable.AcceptChanges();
            Application.Lock();
            Application["OnLineusers"] = userTable;
            Application.UnLock();
    }
    void Session_Start(object sender, EventArgs e) 
    {
        //在新会话启动时运行的代码,用户访问时会触发Session_Start事件,在Session_Start中记录下该用户的信息,存入表中,
//Application["OnLineusers"]存放了所有用户的信息
string sessionid = Session.SessionID; string userIP = Request.UserHostAddress; HttpBrowserCapabilities bc = Request.Browser; string osName = bc.Platform; string Browser=bc.Type; DataTable userTable = (DataTable)Application["OnLineusers"]; if (userTable == null) return; DataRow[] curRow=userTable.Select("SessionId='"+sessionid+"'"); if (curRow.Length == 0) { DataRow newRow = userTable.NewRow(); newRow["SessionID"] = sessionid; newRow[1] = userIP; newRow[2] = Browser; newRow[3] = osName; userTable.Rows.Add(newRow); userTable.AcceptChanges(); Application.Lock(); Application["OnLineusers"] = userTable; Application.UnLock(); } }
   //移除回话结束的Session
  void Session_End(object sender, EventArgs e) { Hashtable onlineuserhash = (Hashtable)Application["OnLineusers"]; onlineuserhash.Remove(Request.UserHostAddress); string sessionid = Session.SessionID; DataTable usertable = (DataTable)Application["OnLineusers"]; if (usertable == null) { return; } foreach (DataRow row in usertable.Select("SessionID='" + sessionid + "'")) { usertable.Rows.Remove(row); } usertable.AcceptChanges(); Application.Lock(); Application["OnLineusers"] = usertable; Application.UnLock(); }

 常用的解决方法:在项目下建一个txt文件存储在线人数,Session_Start,Session_end对txt进行操作

原文地址:https://www.cnblogs.com/huangll/p/2782888.html