以下是我的類文件,
//online.cs(用戶在線檢測)
/*程序實現思路:
該用戶有以下幾個屬性:
name:用戶名
sessionid:用戶id,通過它唯一表示一個用戶
iswhere :附加信息,用戶當前所在位置
lasttime:用戶登陸時間
curtime:本次刷新時間
在客戶端,使用一個iframe,裝載一個刷新頁面,每隔xx秒更新一下他的名字對應的curtime,就表示他仍然在
在服務器端,建立一個守護線程,每隔固定時間就運行一遍,然後判斷當前所有用戶列表中的時間間隔是否超出了
規定的時間,如果超出,則將該用戶從在線列表中刪除,這樣就可以做到檢測用戶是否在線了,而如果再單獨
寫個用戶離線後的處理,就可以解決好多人問到的:用戶意外吊線後的處理。
*/
#define _debug
namespace soholife
{
using system;
using system.data;
using system.data.sqlclient;
using system.collections ;
using system.threading ;
using system.web;
using system.diagnostics;
//定義了一個結構
public struct user
{
public string name;
public datetime lasttime;
public datetime curtime;
public string sessionid;
public string iswhere;
}
//定義在線用戶類
public class onlineuser
{
private static arraylist _alluser ;//定義用戶
public arraylist alluser
{
get{return _alluser;}
set{_alluser=value;}
}
public onlineuser()//構造函數
{
if(_alluser==null)
{
_alluser=new arraylist();
}
}
//功能說明:將當前用戶加入在線列表
//如果該用戶的數據當前仍然在在線列表中,則暫時先不讓該用戶登陸,提示用戶存在
public booladdusertoonline(user user)
{
//需要先判斷用戶是否已經在用戶列表中了
if(_alluser==null)
{
_alluser.add(user);
return (true);
}
else
{
for ( int i = 0 ; i < _alluser.count ; i ++)
{
//循環判斷用戶是否已經存在
soholife.user tempuser = (soholife.user)_alluser[i] ;
if(tempuser.sessionid.equals(user.sessionid) && tempuser.name.equals(user.name))
{
return(false);//用戶已經存在,則直接退出
}
}
_alluser.add(user);
return (true);
}
}
//功能說明:判斷某用戶是否在線,本部分暫時不用
//返回值:true代表在線,false不在
publicboolean isuseronline(string name)
{
//需要先判斷用戶是否已經在用戶列表中了
if(_alluser==null)
{
return (false);
}
else
{
for ( int i = 0 ; i < _alluser.count ; i ++)
{
//循環判斷用戶是否已經存在
soholife.user tempuser = (soholife.user)_alluser[i] ;
if(tempuser.name.equals(name))
{
return(true);
}
}
return (false);
}
}
//功能說明:更新用戶在線時間
//返回值:最新的在線用戶列表
public boolean checkuseronline(string name)
{
//需要先判斷用戶是否已經在用戶列表中了
if(_alluser!=null)
{
for ( int i = 0 ; i < _alluser.count ; i ++)
{
soholife.usertempuser = (soholife.user)_alluser[i] ;
//先判斷當前用戶是否是自己
if(tempuser.name.equals(name))
{
//更新用戶在線時間
tempuser.curtime=datetime.now;
alluser[i]=tempuser;
return(true);
}
}
}
return(false);
}
}
/*
下面開始建立守護線程類:
(注:此處,開始寫的時候本來想做成單件模式的,不過由於以前沒有做過這個東西,所以反而發生
了很多問題,最後決定放棄而使用現有的格式,不過,剛才從開心那裡有對單件有個認識,晚上回去
會再去用用它寫另一種模式)
*/
public class checkonline
{
const int delay_times = 5000 ;//定義執行的時間間隔為5秒
const int delay_seconds=30;//將用戶掉線時間設置為30秒
private thread thread ;//定義內部線程
private static bool _flag=false;//定義唯一標誌
public checkonline()
{
if (!_flag)
{
_flag= true;
this.thread = new thread(new threadstart(threadproc)) ;
thread.name = online user ;
thread.start() ;
}
}
internal void threadproc()
{
while(true)
{
soholife.onlineuser temp=new soholife.onlineuser();//定義一個用戶對象
for (int i=0 ;i< temp.alluser.count;i++)
{
user tmpuser=(user)temp.alluser[i];
//我是將該用戶的最新時間加上80秒,然後和當前時間比較,小與當前時間,
//則表示該用戶已經吊線,則刪除他的記錄
if(tmpuser.curtime.addseconds(delay_seconds).compareto(datetime.now)<0)
{
temp.alluser.removeat(i);
}
}
thread.sleep(delay_times) ;
}
}
}
}
編譯語句為:csc /t:library /out:../bin/online.dll /r:system.dll online.cs