using System; using System.Data; using System.Data.SqlClient; using System.Collections ; using System.Threading ; using System.Web; using System.Diagnostics;
namespace SohoProject { //定义了一个结构 public struct User { public string name; public DateTime lasttime; public DateTime curtime; public string sessionid; public string ip; public string iswhere; }
public class OnLineUser { private static DataTable _alluser;
//只读属性 public DataTable alluser{ get{return _alluser;} }
public OnLineUser() { if(_alluser==null) { //define user list // Declare variables for DataColumn and DataRow objects. _alluser = new DataTable("onlineuser");
DataColumn myDataColumn;
// Create new DataColumn, set DataType, ColumnName and add to DataTable. myDataColumn = new DataColumn(); myDataColumn.DataType = System.Type.GetType("System.String"); myDataColumn.ColumnName = "name"; myDataColumn.AutoIncrement = false; myDataColumn.Caption = "name"; myDataColumn.ReadOnly = false; myDataColumn.Unique = false; _alluser.Columns.Add(myDataColumn);
//功能说明:将当前用户加入在线列表 //如果该用户的数据当前仍然在在线列表中,则暂时先不让该用户登陆,提示用户存在 public bool AddUserToOnLine(User user) { #if DEBUG (new SohoProject.SohoDebug()).WriteToDoc("开始进入<将当前用户加入在线列表>...."); (new SohoProject.SohoDebug()).WriteToDoc("/r/n"); #endif
//开始搜索是否已经存在该用户,如果存在则是改变数据,否则添加新的用户 string strExpr; strExpr = "sessionid='" + user.sessionid + "'"; DataRow[] curUser; // Use the Select method to find all rows matching the filter. #if DEBUG (new SohoProject.SohoDebug()).WriteToDoc("搜索字符串:" + strExpr); (new SohoProject.SohoDebug()).WriteToDoc("/r/n"); #endif
curUser = _alluser.Select(strExpr);
#if DEBUG (new SohoProject.SohoDebug()).WriteToDoc(strExpr); (new SohoProject.SohoDebug()).WriteToDoc(curUser.Length.ToString()); #endif
if (curUser.Length >0 ) { for(int i = 0; i < curUser.Length; i ++) { curUser[i]["curtime"]=DateTime.Now; curUser[i]["iswhere"]=user.iswhere; } } else { //直接加入新的数据 DataRow myRow; try { myRow = _alluser.NewRow(); // Then add the new row to the collection. myRow["name"] = user.name; myRow["ip"] = user.ip; myRow["iswhere"] = user.iswhere; myRow["lasttime"] = user.lasttime; myRow["curtime"] = DateTime.Now; myRow["sessionid"] = user.sessionid; _alluser.Rows.Add(myRow); } catch(Exception e) { throw(new Exception(e + "--------------------" + e.ToString())) ; } } _alluser.AcceptChanges(); return true; }
//功能说明:判断某用户是否在线,本部分暂时不用 //返回值:TRUE代表在线,FALSE不在 public Boolean IsUserOnLine(string name) { //需要先判断用户是否已经在用户列表中了 //开始搜索是否已经存在该用户,如果存在则是改变数据,否则添加新的用户 string strExpr; strExpr = "name ='" + name + "'"; DataRow[] curUser; // Use the Select method to find all rows matching the filter. curUser = _alluser.Select(strExpr);
//OnLineUser alluser= new OnLineUser(); AddUserToOnLine(newuser); } return(false); } }
/* 下面开始建立守护线程类: (注:此处,开始写的时候本来想做成单件模式的,不过由于以前没有做过这个东西,所以反而发生 了很多问题,最后决定放弃而使用现有的格式) */ public class CheckOnline { const int DELAY_TIMES = 10000 ; //定义执行的时间间隔为5秒 const int DELAY_SECONDS=60; //将用户掉线时间设置为30秒