using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Threading;using System.Collections.Generic;//聊天室public class Room{ private static readonly long ClearUserInterval = 300000;//调用定时函数的时间间隔5分钟 private static readonly TimeSpan ExpiringInterval = new TimeSpan(0, 10, 0);//过期的区间10分钟 private static readonly int MessageLimit = 50;//存储的信息的最大数量 private Dictionary<string, ChatUser> chatingUsers = null;//聊天用户的集合 private LinkedList<Msg> chatMessage = null;//消息集合 private Timer timer = null; private object islock = new object(); public Room() { this.chatingUsers = new Dictionary<string, ChatUser>(); this.chatMessage = new LinkedList<Msg>(); //定期清除过期用户 TimerCallback callback = new TimerCallback(this.OnClearExpiredUser);//代理 this.timer = new Timer(callback, null, ClearUserInterval, ClearUserInterval); } private static Room _Instance = new Room(); public static Room Instance//singleton设计模式,保证全局只有一个Room实例 { get { return _Instance; } } //用户是否在聊天 public bool UserIsChatting(string userName) { return this.chatingUsers.ContainsKey(userName); } //获取特定的聊天用户类 public ChatUser GetUser(string userName) { return this.chatingUsers[userName]; } //添加一个聊天用户 public void AddUser(string userName, string password) { lock (islock)//上锁 { this.chatingUsers[userName] = new ChatUser(userName, password); } } //定期执行的函数,踢掉过期用户 private void OnClearExpiredUser(object state) { lock (islock)//防止并发 { List<ChatUser> expiredUsers = new List<ChatUser>();//过期用户 foreach (ChatUser user in this.chatingUsers.Values)//遍历所有用户,找出过期用户 { if (user.IsExpired(ExpiringInterval)) //是否大于等于10分钟 { expiredUsers.Add(user);//加上过期用户 } } //踢出过期用户 foreach (ChatUser user in expiredUsers) { this.chatingUsers.Remove(user.Name); } } } //发送消息 public void SendMessage(string userName, string othername, string message, string isbold, string color, string img) { lock (islock) { if (this.chatMessage.Count >= MessageLimit)//信息量超出最大值,清除一个 { this.chatMessage.RemoveFirst(); } //添加新信息 this.chatMessage.AddLast(new Msg(userName, othername, message, isbold, color, img)); } } public void SendMessage(string message)//发送系统消息 { lock (islock) { if (this.chatMessage.Count >= MessageLimit) { this.chatMessage.RemoveFirst(); } //添加消息 this.chatMessage.AddLast(new Msg(message)); } } //所有消息 public IEnumerable<Msg> GetAllMessages() { return this.chatMessage; } //所有用户 public IEnumerable<ChatUser> GetAllUsers() { return this.chatingUsers.Values; }}

评论