以下是我的类文件,
//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