天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

133 lines
4.1 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.TextUtil;
namespace NSC.Service
{
/// <summary>
/// 功能:会话服务引擎
/// 作者:王昊昇
/// 时间:2012.11.8
/// </summary>
public class SessionServiceEngine :IDisposable
{
/// <summary>
/// 私有构造
/// </summary>
private SessionServiceEngine()
{
SessionList = new Dictionary<string, UserSessionInfo>();
tmr = new System.Timers.Timer();
tmr.Interval = 60000;
tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed);
tmr.Start();
}
/// <summary>
/// 创建会话服务
/// </summary>
/// <returns></returns>
public static SessionServiceEngine CreateSessionService()
{
if (serviceInstance == null)
{
serviceInstance = new SessionServiceEngine();
}
return serviceInstance;
}
static SessionServiceEngine serviceInstance = null;//当前会话服务对象
Dictionary<string, UserSessionInfo> SessionList = null;//会话列表
System.Timers.Timer tmr = null;//会话清理计时器
/// <summary>
/// 处理过期的会话
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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);
}
}
/// <summary>
/// 向会话中添加用户,已存在时更新会话
/// </summary>
/// <param name="user">用户会话信息</param>
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);
}
}
}
/// <summary>
/// 注销指定用户的会话状态
/// </summary>
/// <param name="user">用户会话信息</param>
public void RemoveUser(UserSessionInfo user)
{
if(SessionList.ContainsKey(user.IP))
{
SessionList.Remove(user.IP);
}
}
/// <summary>
/// 查找指定用户
/// </summary>
/// <param name="userName">用户姓名</param>
/// <returns>返回找到的会话数据,找不到时抛出System.InvalidOperationException</returns>
public UserSessionInfo FindUser(string userName)
{
return SessionList.First(p => p.Value.UserName == userName).Value;
}
/// <summary>
/// 释放所有资源
/// </summary>
public void Dispose()
{
tmr.Stop();
tmr.Dispose();
SessionList.Clear();
SessionList = null;
}
}
}