using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.TextUtil;
namespace NSC.Service
{
///
/// 功能:会话服务引擎
/// 作者:王昊昇
/// 时间:2012.11.8
///
public class SessionServiceEngine :IDisposable
{
///
/// 私有构造
///
private SessionServiceEngine()
{
SessionList = new Dictionary();
tmr = new System.Timers.Timer();
tmr.Interval = 60000;
tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed);
tmr.Start();
}
///
/// 创建会话服务
///
///
public static SessionServiceEngine CreateSessionService()
{
if (serviceInstance == null)
{
serviceInstance = new SessionServiceEngine();
}
return serviceInstance;
}
static SessionServiceEngine serviceInstance = null;//当前会话服务对象
Dictionary SessionList = null;//会话列表
System.Timers.Timer tmr = null;//会话清理计时器
///
/// 处理过期的会话
///
///
///
private void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
var s = SessionList.Where(p => Common.TextUtil.DateTimeUtil.DateDiff(p.Value.UpdateTime).TotalMinutes > 20);
foreach (var u in s)
{
SessionList.Remove(u.Key);
}
}
///
/// 向会话中添加用户,已存在时更新会话
///
/// 用户会话信息
public void AddUser(UserSessionInfo user)
{
user.LogonTime = DateTime.Now;
user.UpdateTime = DateTime.Now;
if (SessionList.ContainsKey(user.IP))
{
SessionList.Add(user.IP, user);
}
else
{
if (SessionList[user.IP].UserName == user.UserName && SessionList[user.IP].UserID == user.UserID)
{
SessionList[user.IP] = new UserSessionInfo()
{
AdminLicense = SessionList[user.IP].AdminLicense,
ClientSN = SessionList[user.IP].ClientSN,
IP = SessionList[user.IP].IP,
License = SessionList[user.IP].License,
LogonTime = SessionList[user.IP].LogonTime,
Port = user.Port,
UpdateTime = DateTime.Now,
UserName = SessionList[user.IP].UserName
};
}
else
{
SessionList.Remove(user.IP);
SessionList.Add(user.IP, user);
}
}
}
///
/// 注销指定用户的会话状态
///
/// 用户会话信息
public void RemoveUser(UserSessionInfo user)
{
if(SessionList.ContainsKey(user.IP))
{
SessionList.Remove(user.IP);
}
}
///
/// 查找指定用户
///
/// 用户姓名
/// 返回找到的会话数据,找不到时抛出System.InvalidOperationException
public UserSessionInfo FindUser(string userName)
{
return SessionList.First(p => p.Value.UserName == userName).Value;
}
///
/// 释放所有资源
///
public void Dispose()
{
tmr.Stop();
tmr.Dispose();
SessionList.Clear();
SessionList = null;
}
}
}