using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Applications.Session { public class SessionEngine { public SessionEngine() { Load(); } List SessionList = null;//会话列表 System.Timers.Timer tmr = null; /// /// 装载服务定义 /// private void Load() { tmr = new System.Timers.Timer(); tmr.Interval = 60000; tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed); tmr.Start(); } /// /// 处理过期的会话 /// /// /// private void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { TimeSpan ts = Common.TextUtil.DateTimeUtil.DateDiff(DateTime.Now); var s = SessionList.FindAll(p => Common.TextUtil.DateTimeUtil.DateDiff(p.UpdateTime).TotalMinutes > 20); for (int i = s.Count; i >= 0; i--) { SessionList.RemoveAt(i); } } /// /// 向会话中添加用户,已存在时更新会话 /// /// 用户会话信息 public void AddUser(SessionInfo user) { user.LogonTime = DateTime.Now; user.UpdateTime = DateTime.Now; var s = SessionList.Find(p => p.IP == user.IP); if (s == null) { SessionList.Add(user); } else { if (s.UserName == user.UserName) { s.Port = user.Port; s.UpdateTime = DateTime.Now; } else { SessionList.Remove(s); SessionList.Add(user); } } } /// /// 注销指定用户的会话状态 /// /// 用户会话信息 public void RemoveUser(SessionInfo user) { var s = SessionList.Find(p => p.IP == user.IP); if (s != null) { SessionList.Remove(s); } } /// /// 查找指定用户 /// /// 用户姓名 /// public SessionInfo FindUser(string userName) { return SessionList.Find(p => p.UserName == userName); } } }