在最近的學習中,參考其他資源,做了一個簡單的在線人員顯示的功能,總結了一下,思路如下:
1、定義一個全局的內存來作為在線人員列表
2、通過實時判斷用戶session值,來判斷某個用戶的登錄或離線
3、對于用戶的上線和離線,通過添加用戶到內存中,或刪除內存中的用戶列表中的用戶來實現
下面是實現該功能的類:
1 public static class UserOnline 2 { 3 /// <summary> 4 /// 獲取或設置在線列表 5 /// </summary> 6 public static Hashtable OnlineUserList 7 { 8 get 9 { 10 if (HttpContext.Current.application["OnlineUserList"] == null) 11 { 12 Hashtable onlineUserList = new Hashtable(); 13 HttpContext.Current.Application["OnlineUserList"] = onlineUserList; 14 } 15 16 return (Hashtable)HttpContext.Current.Application["OnlineUserList"]; 17 } 18 set 19 { 20 HttpContext.Current.Application["OnlineUserList"] = value; 21 } 22 } 23 24 /// <summary> 25 /// 添加在線成員 26 /// </summary> 27 public static bool OnlineUserList_Add(string key, string value) 28 { 29 try 30 { 31 if (OnlineUserList.Contains(key)) 32 OnlineUserList[key] = value; 33 else 34 OnlineUserList.Add(key, value); 35 return true; 36 } 37 catch 38 { 39 return false; 40 } 41 } 42 43 /// <summary> 44 /// 添加在線成員 45 /// </summary> 46 public static bool OnlineUserList_Add(string key) 47 { 48 string value = DateTime.Now.ToString(); 49 return OnlineUserList_Add(key, value); 50 } 51 52 /// <summary> 53 /// 離線刪除用戶 54 /// </summary> 55 public static bool OnlineUserList_Delete(string key) 56 { 57 bool re = false; 58 if (OnlineUserList.Contains(key)) 59 { 60 Hashtable userList = OnlineUserList; 61 userList.Remove(key); 62 OnlineUserList = userList; 63 return true; 64 } 65 return re; 66 } 67 68 /// <summary> 69 /// 判斷用戶是否在線 70 /// </summary> 71 public static bool UserIsOnline(string adminName) 72 { 73 OnlineClearUserOutTimeInOnLineList(); 74 return OnlineUserList.Contains(adminName) ? true : false; 75 } 76 77 /// <summary> 78 /// 刪除超時在線用戶 79 /// </summary> 80 public static void OnlineClearUserOutTimeInOnLineList() 81 { 82 int OnlineTimeOut = 20; 83 Hashtable list = new Hashtable(); 84 Hashtable temList = new Hashtable(); 85 list = OnlineUserList; 86 temList = new Hashtable(list); 87 foreach (DictionaryEntry de in temList) 88 { 89 //刪除超時 90 DateTime onlineTime = Convert.ToDateTime(de.Value); 91 TimeSpan timeSpan = DateTime.Now - onlineTime; 92 93 //在線時間和當前時間間隔大于超時分鐘數就刪除(注:用戶非法關閉瀏覽器) 94 if (timeSpan.TotalMinutes >= (double)OnlineTimeOut) 95 { 96 list.Remove(de.Key); 97 } 98 99 }100 101 OnlineUserList = list;102 }103 104 }
在用戶登錄成功的時候,添加改用戶的惟一值到內存列表中
該用戶的Session結束前進行刪除即可。
新聞熱點
疑難解答