ASP.NET C# 實現實時用戶在線

public static class UserOnline
{
    /// <summary>
    /// 獲取或設置在線列表
    /// </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>
    /// 刪除超時在線用戶
    /// </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)
        {
            //刪除超時
            DateTime onlineTime = Convert.ToDateTime(de.Value);
            TimeSpan timeSpan = DateTime.Now - onlineTime;

            //在線時間和當前時間間隔大於超時分鐘數就刪除(注:用戶非法關閉瀏覽器)
            if (timeSpan.TotalMinutes >= (double)OnlineTimeOut)
            {
                list.Remove(de.Key);
            }

        }

        OnlineUserList = list;
    }

}
相關文章
相關標籤/搜索