private void BroadcastMessage(ChatEventArgs e) { ChatEventHandler temp = ChatEvent; if (temp != null) { //循环将在线的用户广播信息 foreach (ChatEventHandler handler in temp.GetInvocationList()) { //异步方式调用多路广播委托的调用列表中的ChatEventHandler handler.BeginInvoke(this, e, new AsyncCallback(EndAsync), null); } } }
public void Leave() { if (this.name == null) { return; } lock (syncObj) { chatters.Remove(this.name); } ChatEvent -= myEventHandler; ChatEventArgs e = new ChatEventArgs(); e.msgType = MessageType.UserLeave; e.name = this.name; this.name = null; BroadcastMessage(e); }
public void Whisper(string to, string msg) { ChatEventArgs e = new ChatEventArgs(); e.msgType = MessageType.ReceiveWhisper; e.name = this.name; e.message = msg; try { ChatEventHandler chatterTo;//创建一个临时委托实例 lock (syncObj) { chatterTo = chatters[to]; //查找成员字典中,找到要接收者的委托调用 } chatterTo.BeginInvoke(this, e, new AsyncCallback(EndAsync), null); //异步方式调用接收者的委托调用 } catch (KeyNotFoundException) { } }
public string[] Join(string name) { bool userAdded = false; myEventHandler = new ChatEventHandler(MyEventHandler); //将MyEventHandler方法作为参数传递给委托 lock (syncObj) //线程的同步性,同步访问多个线程的任何变量,利用lock(独占锁),确保数据访问的唯一性。 { if (!chatters.ContainsKey(name) && name != "" && name != null) { this.name = name; chatters.Add(name, MyEventHandler); userAdded = true; } } if (userAdded) { callback = OperationContext.Current.GetCallbackChannel <IChatCallback>(); //获取当前操作客户端实例的通道给IChatCallback接口的实例callback,此通道是一个定义为IChatCallback类型的泛类型,通道的类型是事先服务契约协定好的双工机制。 ChatEventArgs e = new ChatEventArgs(); //实例化事件消息类ChatEventArgs e.msgType = MessageType.UserEnter; e.name = name; BroadcastMessage(e); ChatEvent += myEventHandler; string[] list = new string[chatters.Count]; //以下代码返回当前进入聊天室成员的称列表 lock (syncObj) { chatters.Keys.CopyTo(list, 0);//将字典中记录的用户信息复制到数组中返回。 } return(list); } else { return(null); } }