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

📄 chatclient.cs

📁 基于SOCKET的聊天室
💻 CS
📖 第 1 页 / 共 2 页
字号:
			this.Controls.Add(this.groupBox1);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.cbPrivate);
			this.Controls.Add(this.lstUsers);
			this.Controls.Add(this.btnSend);
			this.Controls.Add(this.tbSendContent);
			this.Name = "ChatClientForm";
			this.Text = "ChatClient";
			this.Closing += new System.ComponentModel.CancelEventHandler(this.ChatClientForm_Closing);
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new ChatClientForm());
		}


		//ServerResponse()方法用于接收从服务器发回的信息,
		//根据不同的命令,执行相应的操作
		private void ServerResponse()
		{
			//定义一个byte数组,用于接收从服务器端发送来的数据,
			//每次所能接收的数据包的最大长度为1024个字节
			byte[] buff=new byte[1024];
			string msg;
			int len;
			try
			{
				if(!Stream.CanRead)
				{
					return;
				}

				stopFlag = false;
				while(!stopFlag)
				{
					//从流中得到数据,并存入到buff字符数组中
					len=Stream.Read(buff,0,buff.Length);

					if (len < 1)
					{
						Thread.Sleep(200);
						continue;
					}
					
					//将字符数组转化为字符串
					msg=System.Text.Encoding.Default.GetString(buff,0,len);
					msg.Trim();

					string[] tokens=msg.Split(new Char[]{'|'});
					//tokens[0]中保存了命令标志符(LIST或JOIN或QUIT)
					
					if (tokens[0].ToUpper()== "OK")
					{
						//处理响应
						add("命令执行成功");
					}
					else if (tokens[0].ToUpper()== "ERR")
					{
						//命令执行错误
						add("命令执行错误:" + tokens[1]);
					}
					else if(tokens[0]== "LIST")
					{
						//此时从服务器返回的消息格式:
						//命令标志符(LIST)|用户名1|用户名|2...(所有在线用户名)|
						add("获得用户列表");
						//更新在线用户列表
						lstUsers.Items.Clear();
						for(int i=1;i<tokens.Length-1;i++)
						{
							lstUsers.Items.Add(tokens[i].Trim());
						}
					}
					else if(tokens[0]== "JOIN")
					{
						//此时从服务器返回的消息格式:
						//命令标志符(JOIN)|刚刚登入的用户名|
						add(tokens[1]+" "+"已经进入了聊天室");
						this.lstUsers.Items.Add(tokens[1]);
						if (this.tbUserName.Text ==tokens[1]) 
						{
							this.state = CONNECTED;
						}
					}
					else if(tokens[0]== "QUIT")
					{
						if (this.lstUsers.Items.IndexOf(tokens[1])>-1)
						{
							this.lstUsers.Items.Remove(tokens[1]);
						}
						add("用户:" + tokens[1] + " 已经离开");
					}
					else
					{
						//如果从服务器返回的其他消息格式,
						//则在ListBox控件中直接显示
						add(msg);
					}	
				}
				//关闭连接
				tcpClient.Close();
			}
			catch
			{
				add("网络发生错误");
			}
		}

		private void add(string msg)
		{
			if (!color.IsEmpty)
			{
				this.rtbMsg.SelectionColor = color;
			}
			this.rtbMsg.SelectedText = msg + "\n";
		}

		//当点击“发送”按钮时,便会进入btnSend_Click处理程序。
		//在btnSend_Click处理程序中,如果不是私聊,
		//将“CHAT”命令发送给服务器,
		//否则(为私聊),将“PRIV”命令发送给服务器,
		//注意命令格式一定要与服务器端的命令格式一致
		private void btnSend_Click(object sender, System.EventArgs e)
		{
			try
			{
				if(!this.cbPrivate.Checked)
				{
					//此时命令的格式是:
					//命令标志符(CHAT)|发送者的用户名:发送内容|
					string message="CHAT|"+ this.tbUserName.Text +":"+
						tbSendContent.Text+"|";
					tbSendContent.Text="";
					tbSendContent.Focus();
					//将字符串转化为字符数组
					Byte[]outbytes=System.Text.Encoding.Default.GetBytes(
						message.ToCharArray());
					Stream.Write(outbytes,0,outbytes.Length);
					
				}
				else
				{
					if(lstUsers.SelectedIndex==-1)
					{
						MessageBox.Show("请在列表中选择一个用户","提示信息",
							MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
						return;
					}
					string receiver=lstUsers.SelectedItem.ToString();
					//消息的格式是:
					//命令标志符(PRIV)|发送者的用户名|接收者的用户名|发送内容|
					string message="PRIV|"+this.tbUserName.Text+"|"+receiver+"|"+
						tbSendContent.Text+"|";
					tbSendContent.Text="";
					tbSendContent.Focus();
					//将字符串转化为字符数组
					byte[] outbytes=System.Text.Encoding.ASCII.GetBytes(
						message.ToCharArray());
					Stream.Write(outbytes,0,outbytes.Length);
					
				}
			}
			catch
			{
				this.rtbMsg.AppendText("网络发生错误");
			}

		}


		//连接聊天服务器
		private void btnLogin_Click(object sender, System.EventArgs e)
		{
			if (state == CONNECTED)
			{
				return;
			}

			if(this.tbUserName.Text.Length==0)
			{
				MessageBox.Show("请输入您的呢称!","提示信息",
					MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
				this.tbUserName.Focus();
				return;
			}
			try
			{
				//创建一个客户端套接字,它是Login的一个公共属性,
				//将被传递给ChatClient窗体
				tcpClient=new TcpClient();
				//向指定的IP地址的服务器发出连接请求
				tcpClient.Connect(IPAddress.Parse(txtHost.Text),
					Int32.Parse(txtPort.Text));
				//获得与服务器数据交互的流通道(NetworkStream)
				Stream=tcpClient.GetStream();

				//启动一个新的线程,执行方法this.ServerResponse(),
				//以便来响应从服务器发回的信息
				Thread thread=new Thread(new ThreadStart(this.ServerResponse));
				thread.Start();

				//向服务器发送“CONN”请求命令,
				//此命令的格式与服务器端的定义的格式一致,
				//命令格式为:命令标志符(CONN)|发送者的用户名|
				string cmd="CONN|"+this.tbUserName.Text+"|";
				//将字符串转化为字符数组
				Byte[] outbytes=System.Text.Encoding.Default.GetBytes(
					cmd.ToCharArray());
				Stream.Write(outbytes,0,outbytes.Length);

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}

		}

		//设置字体颜色
		private void btnColor_Click(object sender, System.EventArgs e)
		{
			ColorDialog colorDialog1 = new ColorDialog();
			colorDialog1.Color = this.rtbMsg.SelectionColor;

			if(colorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK && 
				colorDialog1.Color !=this.rtbMsg.SelectionColor)
			{
				this.rtbMsg.SelectionColor = colorDialog1.Color;
				color = colorDialog1.Color;
			}
		}

		//当单击“离开”按钮时,便进入了btnExit_Click 处理程序。
		//在btnExit_Click 处理程序中,
		//将“EXIT”命令发送给服务器,此命令格式要与服务器端的命令格式一致
		private void btnExit_Click_1(object sender, System.EventArgs e)
		{
			if (state == CONNECTED) 
			{
				string message="EXIT|"+this.tbUserName.Text+"|";
				//将字符串转化为字符数组
				Byte[]outbytes=System.Text.Encoding.Default.GetBytes(
					message.ToCharArray());
				Stream.Write(outbytes,0,outbytes.Length);

				this.state = CLOSED;
				this.stopFlag = true;
				this.lstUsers.Items.Clear();
			}
		}

		private void ChatClientForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			btnExit_Click_1(sender, e);
		}


	}
}

⌨️ 快捷键说明

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