ASP.NET實(shí)現(xiàn)在線人員實(shí)時(shí)統(tǒng)計(jì)顯示
做了一個(gè)簡(jiǎn)單的在線人員顯示的功能,總結(jié)了一下,思路如下:
1、定義一個(gè)全局的內(nèi)存來(lái)作為在線人員列表
2、通過(guò)實(shí)時(shí)判斷用戶Session值,來(lái)判斷某個(gè)用戶的登錄或離線
3、對(duì)于用戶的上線和離線,通過(guò)添加用戶到內(nèi)存中,或刪除內(nèi)存中的用戶列表中的用戶來(lái)實(shí)現(xiàn)
在用戶登錄成功的時(shí)候,添加改用戶的惟一值到內(nèi)存列表中
該用戶的Session結(jié)束前進(jìn)行刪除即可。
下面是實(shí)現(xiàn)該功能的類:
public static class UserOnline { /// <summary> /// 獲取或設(shè)置在線列表 /// </summary> public static Hashtable OnlineUserList { get { if (HttpContext.Current.Application["OnlineUserList"] == null) { Hashtable onlineUserList = new Hashtable(); HttpContext.Current.Application["OnlineUserList"] = onlineUserList; } return (Hashtable)HttpContext.Current.Application["OnlineUserList"]; } set { HttpContext.Current.Application["OnlineUserList"] = value; } } /// <summary> /// 添加在線成員 /// </summary> public static bool OnlineUserList_Add(string key, string value) { try { if (OnlineUserList.Contains(key)) OnlineUserList[key] = value; else OnlineUserList.Add(key, value); return true; } catch { return false; } } /// <summary> /// 添加在線成員 /// </summary> public static bool OnlineUserList_Add(string key) { string value = DateTime.Now.ToString(); return OnlineUserList_Add(key, value); } /// <summary> /// 離線刪除用戶 /// </summary> public static bool OnlineUserList_Delete(string key) { bool re = false; if (OnlineUserList.Contains(key)) { Hashtable userList = OnlineUserList; userList.Remove(key); OnlineUserList = userList; return true; } return re; } /// <summary> /// 判斷用戶是否在線 /// </summary> public static bool UserIsOnline(string adminName) { OnlineClearUserOutTimeInOnLineList(); return OnlineUserList.Contains(adminName) ? true : false; } /// <summary> /// 刪除超時(shí)在線用戶 /// </summary> public static void OnlineClearUserOutTimeInOnLineList() { int OnlineTimeOut = 20; Hashtable list = new Hashtable(); Hashtable temList = new Hashtable(); list = OnlineUserList; temList = new Hashtable(list); foreach (DictionaryEntry de in temList) { //刪除超時(shí) DateTime onlineTime = Convert.ToDateTime(de.Value); TimeSpan timeSpan = DateTime.Now - onlineTime; //在線時(shí)間和當(dāng)前時(shí)間間隔大于超時(shí)分鐘數(shù)就刪除(注:用戶非法關(guān)閉瀏覽器) if (timeSpan.TotalMinutes >= (double)OnlineTimeOut) { list.Remove(de.Key); } } OnlineUserList = list; } }
原文鏈接:ASP.NET實(shí)現(xiàn)在線人員實(shí)時(shí)統(tǒng)計(jì)顯示