⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatclient.cs

📁 进程间通信精华资料,包括好多源码,和文章,都是个人收集的.主要是vc和c#方面的
💻 CS
📖 第 1 页 / 共 2 页
字号:
			this.Load += new System.EventHandler(this.Form1_Load);
			this.Closed += new System.EventHandler(this.Form1_Closed);
			this.grpClientChatBox.ResumeLayout(false);
			this.grpSend.ResumeLayout(false);
			this.groupBox1.ResumeLayout(false);
			this.grpAuthenticate.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private bool StartHttpServer()
		{			
			bool result = false;
			IDictionary id = null;
			string uname = txtProxyUserName.Text;
			string pwd = txtProxyPassword.Text;
			ICredentials ic = null;
			try
			{	
				SoapClientFormatterSinkProvider scl = new SoapClientFormatterSinkProvider();
				SoapServerFormatterSinkProvider ssr = new SoapServerFormatterSinkProvider();
				ssr.TypeFilterLevel = TypeFilterLevel.Full;
		
				IWebProxy proxy = new WebProxy("proxy.sharda.mahindrabt.com", 80);				
				ic = new NetworkCredential(uname, pwd);
				proxy.Credentials = ic;

				id = new Hashtable();
				id["port"] = 0;
				id["typeFilterLevel"] = TypeFilterLevel.Full;
				id["name"] = System.Guid.NewGuid().ToString();

				HttpChannel htc = new HttpChannel(id, scl, ssr);				
				ChannelServices.RegisterChannel(htc);
				this.SetChannelProxy(htc, proxy);

				this.im = (IMediator) Activator.GetObject(typeof (IMediator), this.httpServerUrl);				
				result = true;
			}
			catch (RemotingException ex)
			{
				MessageBox.Show(ex.Message + " Stact trace: " + ex.StackTrace);					
			}
			finally
			{				
			}
			return result;
		}

		private void SetChannelProxy( HttpChannel channel, IWebProxy proxy )
		{ 
			//get the channel data
			FieldInfo clientChannelFieldInfo =  typeof(HttpChannel).GetField("_clientChannel", BindingFlags.Instance | BindingFlags.NonPublic);
			//cast it to httpclientchannel to get an access to IWebProxy Class.
			HttpClientChannel clientChannel = (HttpClientChannel)   clientChannelFieldInfo.GetValue(channel);
			//get Proxy object
			FieldInfo proxyObjectFieldInfo = typeof(HttpClientChannel).GetField("_proxyObject", BindingFlags.Instance | BindingFlags.NonPublic);
			//set up proxy explicitly.
			proxyObjectFieldInfo.SetValue(clientChannel, proxy );
		}

		private bool StartTcpServer()
		{
			bool result = false;
			try
			{
				BinaryClientFormatterSinkProvider bcfs = new BinaryClientFormatterSinkProvider();
				BinaryServerFormatterSinkProvider bsfs = new BinaryServerFormatterSinkProvider();
				bsfs.TypeFilterLevel = TypeFilterLevel.Full;

				IDictionary id = new Hashtable();
				id = new Hashtable();
				id["port"] = 0;
				id["typeFilterLevel"] = TypeFilterLevel.Full;
				id["name"] = System.Guid.NewGuid().ToString();

				TcpChannel tcc = new TcpChannel(id, bcfs, bsfs);
				ChannelServices.RegisterChannel(tcc);
				this.im = (IMediator) Activator.GetObject(typeof(IMediator), this.tcpServerUrl);
				result = true;

			}
			catch (RemotingException ex)
			{
				MessageBox.Show(ex.Message + " Stact trace: " + ex.StackTrace);
			}
			finally
			{
			}
			return result;
		}

		private void btnConnect_Click(object sender, System.EventArgs e)
		{
			// StartHttpServer();
			if (txtUserName.Text.CompareTo(string.Empty) == 0)
			{
				MessageBox.Show("Please enter user name.");
			}
			else
			{
				StartTcpServer();

				if (this.im != null)
				{
					this.em = new EventsClass();
					this.em.UserName = this.txtUserName.Text;
					this.em.Message = "Hi!! I'm joining chat..";

					this.em.ClientListHandler += new GetClientsList(this.em_ClientListHandler);
					this.em.WelComeHandler += new WelComeMessage(this.em_WelComeHandler);
					this.em.GetMessageFromOthersHandler += new GetMessageFromOthers(this.em_GetMessageFromOthersHandler);
					this.em.UserLeftHandler += new UserLeftChat(this.em_UserLeftHandler);
					try
					{	
						this.im.ConnectToChat(em);
						this.btnConnect.Enabled = false;
						this.stsConnected.Text = em.UserName + " successfully connected.";
						this.Text = em.UserName;
						this.grpSend.Enabled = true;
						this.txtUserName.Enabled = false;
						this.txtMessage.BackColor =  Color.LightCyan;
						this.txtSendMessage.BackColor = Color.LightYellow;
						this.grpClientChatBox.BackColor = Color.LightSkyBlue;
					}
					catch (RemotingException ex)
					{
						this.lblErrorMessage.Text = ex.Message;
						MessageBox.Show("Exception occured. " + ex.Message);
						this.ReleaseHandlers();
					}
					catch (System.Net.Sockets.SocketException socEx)
					{
						this.lblErrorMessage.Text = socEx.Message;
						MessageBox.Show("Exception occured. " + socEx.Message);
						this.ReleaseHandlers();
					}
					catch (Exception ex)
					{
						this.lblErrorMessage.Text = ex.Message;
						MessageBox.Show("Exception occured. " + ex.Message);
						this.ReleaseHandlers();
					}
				}
			}
		}

		private void ReleaseHandlers()
		{
			try
			{
				this.em.ClientListHandler -= new GetClientsList(this.em_ClientListHandler);
				this.em.WelComeHandler -= new WelComeMessage(this.em_WelComeHandler);
				this.em.GetMessageFromOthersHandler -= new GetMessageFromOthers(this.em_GetMessageFromOthersHandler);
				this.em.UserLeftHandler -= new UserLeftChat(this.em_UserLeftHandler);
			}
			catch (Exception ex)
			{
				MessageBox.Show("No handlers to release. Error: " + ex.Message);
			}
		}

		public void em_ClientListHandler(IClientImplement ici)
		{	
			this.clientList = ici.ClientList;
			Thread th = new Thread(new ThreadStart(this.GetClientList));
			th.Start();
		}

		private void GetClientList()
		{
			this.lstUsers.Items.Clear();
			foreach (IClientImplement icc in this.clientList)
			{
				this.lstUsers.Items.Add(icc.UserName);
			}
			this.lstUsers.BackColor = Color.LightBlue;
			this.lblUserCount.Text = "There are currently " + this.clientList.Count.ToString() + " user connected.";
		}

		public void em_WelComeHandler(IClientImplement ici)
		{
			this.iciClient = ici;
			Thread th = new Thread(new ThreadStart(this.NewUserJoined));
			th.Start();
		}

		private void NewUserJoined()
		{			
			this.txtMessage.AppendText(Environment.NewLine);
			this.txtMessage.AppendText(this.iciClient.UserName + " joined chat at: " + DateTime.Now.ToString());			
		}

		private void btnSend_Click(object sender, System.EventArgs e)
		{
			Thread th = new Thread(new ThreadStart(this.SendMessage));
			th.Start();
		}

		private void SendMessage()
		{
			if (this.txtSendMessage.Text.CompareTo(string.Empty) != 0)
			{
				this.em.Message = txtSendMessage.Text.Trim();
				em.ReceiverName = "ALL";
				this.im.SendMessageToAll(em);
				this.txtSendMessage.Text = string.Empty;
			}
		}

		public void em_GetMessageFromOthersHandler(IClientImplement ici)
		{
			bool isAdded = false;
			this.iciClient = ici;
			Thread th = new Thread(new ThreadStart(this.GetMessageFromOtherClients));
			th.Start();
			IDictionaryEnumerator ide = this.hsPrivateWindows.GetEnumerator();
			while (ide.MoveNext())
			{
				if (ide.Key.ToString().CompareTo(this.iciClient.UserName) == 0)
				{
					isAdded = true;
				}
			}
			if (!isAdded)
			{			
				if (this.iciClient.ReceiverName.CompareTo(this.txtUserName.Text) == 0)
				{
					this.hsPrivateWindows.Add(this.iciClient.UserName, true);
					Thread th1 = new Thread(new ThreadStart(this.OpenPrivateChatWindow));
					th1.Start();
				}
			}
		}

		private void OpenPrivateChatWindow()
		{
			PrivateChat pc = new PrivateChat();
			pc.Text = this.txtUserName.Text + " is chatting with " + this.iciClient.UserName;
			pc.CallerName = this.iciClient.UserName;
			pc.MyName = this.txtUserName.Text;
			pc.UserLeft += new PrivateUserLeft(this.RemoveFromPrivateList);
			pc.ShowDialog();
		}

		private void GetMessageFromOtherClients()
		{			
//			if (this.iciClient.ReceiverName.CompareTo(this.txtUserName.Text) == 0)
//			{
//				this.txtMessage.AppendText(Environment.NewLine);
//				this.txtMessage.AppendText("Private from " + this.iciClient.UserName + " says: " + iciClient.Message);				
//			}
//			else 
			if (this.iciClient.ReceiverName.CompareTo("ALL") == 0)
			{
				this.txtMessage.AppendText(Environment.NewLine);
				this.txtMessage.AppendText(this.iciClient.UserName + " says: " + iciClient.Message);
			}
		}

		private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			try
			{
				this.ReleaseHandlers();
				this.im.RemoveMe(em);
			}
			catch (Exception ex)
			{
				MessageBox.Show("Server may be closed..." + ex.Message);
			}
		}

		private void Form1_Closed(object sender, System.EventArgs e)
		{
			this.ReleaseHandlers();			
		}

		public void em_UserLeftHandler(IClientImplement ici)
		{			
			this.iciClient = ici;			
			Thread thLeft = new Thread(new ThreadStart(this.UserLeftChatRoom));
			thLeft.Start();
		}

		private void UserLeftChatRoom()
		{
			this.txtMessage.AppendText("\n" + this.iciClient.UserName + " left chat at: " + DateTime.Now.ToString());
		}

		private void txtSendMessage_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyValue == 13)
			{
				Thread th = new Thread(new ThreadStart(SendMessage));
				th.Start();
			}
		}

		private void lstUsers_DoubleClick(object sender, System.EventArgs e)
		{
			bool isAdded = false;
			IDictionaryEnumerator ide = this.hsPrivateWindows.GetEnumerator();

			while (ide.MoveNext())
			{
				if (ide.Key.ToString().CompareTo(this.iciClient.UserName) == 0)
				{
					isAdded = true;
				}
			}
			if (!isAdded)
			{
				Thread th = new Thread(new ThreadStart(this.BeginPrivateChat));
				th.Start();
			}
		}

		private void BeginPrivateChat()
		{
			this.hsPrivateWindows.Add(this.lstUsers.SelectedItem.ToString(), true);
			PrivateChat pc = new PrivateChat();
			pc.Text = this.txtUserName.Text + " is chatting with " + this.lstUsers.SelectedItem.ToString();
			pc.CallerName = this.lstUsers.SelectedItem.ToString();
			pc.MyName = this.txtUserName.Text;
			pc.UserLeft += new PrivateUserLeft(this.RemoveFromPrivateList);
			pc.ShowDialog();
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
			SplashScreen ss = new SplashScreen();			
			ss.Refresh();
			ss.ShowDialog();			
		}

		public void RemoveFromPrivateList(string userName)
		{
			Hashtable hs = new Hashtable();			
			IDictionaryEnumerator ide = this.hsPrivateWindows.GetEnumerator();
			while (ide.MoveNext())
			{
				string uName = Convert.ToString(ide.Key);
				if (uName.CompareTo(userName) == 0)
				{
					continue;
				}
				else
				{
					hs.Add(uName, true);
				}
			}
			this.hsPrivateWindows.Clear();
			ide = hs.GetEnumerator();
			while (ide.MoveNext())
			{
				this.hsPrivateWindows.Add(ide.Key, ide.Value);
			}			
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -