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秒