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

📄 form1.cs

📁 聊天室程序的代码下载(客户端与服务器器端)
💻 CS
字号:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace test_socket_client
{
	/// <summary>
	/// Form1 的摘要说明。
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.Button button3;
		private System.Windows.Forms.TextBox textBox1;
		private System.Windows.Forms.CheckBox checkBox1;
		private System.Windows.Forms.StatusBar statusBar1;
		private TcpClient clientsocket;
		private string serveraddress="127.0.0.1";
		private int serverport = 5555;
		private NetworkStream ns;
		private StreamReader sr;
		private bool connected = false;
		private bool keepalive = true;
		private string clientname = "lixj";
		private Thread th;
		private System.Windows.Forms.ListBox lbChatters;
		private System.Windows.Forms.RichTextBox rtbChatIn;
		private System.Windows.Forms.Button btnSend;
		private System.Windows.Forms.Button btnDisconnect;
		private System.Windows.Forms.TextBox textBox2;
		private System.Windows.Forms.Label label1;
		/// <summary>
		/// 必需的设计器变量。
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Windows 窗体设计器支持所必需的
			//
			InitializeComponent();
			//
			// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
			//
		}

		/// <summary>
		/// 清理所有正在使用的资源。
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows 窗体设计器生成的代码
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{
			this.lbChatters = new System.Windows.Forms.ListBox();
			this.rtbChatIn = new System.Windows.Forms.RichTextBox();
			this.button1 = new System.Windows.Forms.Button();
			this.button3 = new System.Windows.Forms.Button();
			this.btnSend = new System.Windows.Forms.Button();
			this.textBox1 = new System.Windows.Forms.TextBox();
			this.checkBox1 = new System.Windows.Forms.CheckBox();
			this.statusBar1 = new System.Windows.Forms.StatusBar();
			this.btnDisconnect = new System.Windows.Forms.Button();
			this.textBox2 = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.SuspendLayout();
			// 
			// lbChatters
			// 
			this.lbChatters.ItemHeight = 12;
			this.lbChatters.Location = new System.Drawing.Point(8, 24);
			this.lbChatters.Name = "lbChatters";
			this.lbChatters.Size = new System.Drawing.Size(160, 196);
			this.lbChatters.TabIndex = 0;
			// 
			// rtbChatIn
			// 
			this.rtbChatIn.Location = new System.Drawing.Point(176, 24);
			this.rtbChatIn.Name = "rtbChatIn";
			this.rtbChatIn.Size = new System.Drawing.Size(368, 312);
			this.rtbChatIn.TabIndex = 2;
			this.rtbChatIn.Text = "";
			// 
			// button1
			// 
			this.button1.Location = new System.Drawing.Point(40, 256);
			this.button1.Name = "button1";
			this.button1.TabIndex = 3;
			this.button1.Text = "连 接";
			this.button1.Click += new System.EventHandler(this.button1_Click);
			// 
			// button3
			// 
			this.button3.Enabled = false;
			this.button3.Location = new System.Drawing.Point(40, 320);
			this.button3.Name = "button3";
			this.button3.TabIndex = 5;
			this.button3.Text = "开始记录";
			// 
			// btnSend
			// 
			this.btnSend.Location = new System.Drawing.Point(472, 344);
			this.btnSend.Name = "btnSend";
			this.btnSend.TabIndex = 6;
			this.btnSend.Text = "发 送";
			this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
			// 
			// textBox1
			// 
			this.textBox1.Location = new System.Drawing.Point(176, 344);
			this.textBox1.Name = "textBox1";
			this.textBox1.Size = new System.Drawing.Size(280, 21);
			this.textBox1.TabIndex = 7;
			this.textBox1.Text = "";
			// 
			// checkBox1
			// 
			this.checkBox1.Location = new System.Drawing.Point(40, 344);
			this.checkBox1.Name = "checkBox1";
			this.checkBox1.TabIndex = 8;
			this.checkBox1.Text = "悄悄话";
			// 
			// statusBar1
			// 
			this.statusBar1.Location = new System.Drawing.Point(0, 375);
			this.statusBar1.Name = "statusBar1";
			this.statusBar1.Size = new System.Drawing.Size(552, 22);
			this.statusBar1.TabIndex = 9;
			// 
			// btnDisconnect
			// 
			this.btnDisconnect.Enabled = false;
			this.btnDisconnect.Location = new System.Drawing.Point(40, 288);
			this.btnDisconnect.Name = "btnDisconnect";
			this.btnDisconnect.TabIndex = 4;
			this.btnDisconnect.Text = "断开连接";
			this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
			// 
			// textBox2
			// 
			this.textBox2.Location = new System.Drawing.Point(8, 232);
			this.textBox2.Name = "textBox2";
			this.textBox2.Size = new System.Drawing.Size(160, 21);
			this.textBox2.TabIndex = 10;
			this.textBox2.Text = "";
			// 
			// label1
			// 
			this.label1.ForeColor = System.Drawing.SystemColors.Desktop;
			this.label1.Location = new System.Drawing.Point(192, 8);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(100, 16);
			this.label1.TabIndex = 11;
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
			this.ClientSize = new System.Drawing.Size(552, 397);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.textBox2);
			this.Controls.Add(this.statusBar1);
			this.Controls.Add(this.checkBox1);
			this.Controls.Add(this.textBox1);
			this.Controls.Add(this.btnSend);
			this.Controls.Add(this.button3);
			this.Controls.Add(this.btnDisconnect);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.rtbChatIn);
			this.Controls.Add(this.lbChatters);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
			this.MaximizeBox = false;
			this.Name = "Form1";
			this.Text = "Form1";
			this.Closed += new System.EventHandler(this.Form1_Closed);
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
		private void EstablishConnection() 
		{ 
			statusBar1.Text = "正在连接到服务器"; 
			try 
			{ 
				clientsocket = new TcpClient(serveraddress,serverport); 
				ns = clientsocket.GetStream(); 
				sr = new StreamReader(ns); 
				connected = true; 
				RegisterWithServer();
			} 
			catch (Exception ex) 
			{ 
				MessageBox.Show(ex.Message,"错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
				statusBar1.Text = "已断开连接"; 
				this.keepalive = false;
			} 

		}  
		private void RegisterWithServer() 
		{ 
			try 
			{ 
				string command = "CONN|" + this.textBox2.Text.ToString(); 
				Byte[] outbytes = System.Text.Encoding.Default.GetBytes(command.ToCharArray()); 
				ns.Write(outbytes,0,outbytes.Length); 


				string serverresponse = sr.ReadLine(); 
				serverresponse.Trim(); 
				string[] tokens = serverresponse.Split(new Char[]{'|'}); 
				if(tokens[0] == "LIST") 
				{ 
					statusBar1.Text = "已连接"; 
					btnDisconnect.Enabled = true; 
				} 
				for(int n=1; n<tokens.Length;n++)
					lbChatters.Items.Add(tokens[n].Trim(new char[]{'\r','\n'})); 
				this.Text = this.textBox2.Text.ToString() + ":已连接到服务器"; 
				this.button1.Enabled = false;


			} 
			catch (Exception) 
			{ 
				MessageBox.Show("注册时发生错误!","错误", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
			} 
		}  
		private void ReceiveChat() 
		{  
			while (keepalive) 
			{ 
				try 
				{ 
					Byte[] buffer = new Byte[2048]; 
					ns.Read(buffer,0,buffer.Length); 
					string chatter = System.Text.Encoding.Default.GetString(buffer); 
					string[] tokens = chatter.Split(new Char[]{'|'}); 

					if (tokens[0] == "CHAT") 
					{ 
						rtbChatIn.AppendText(tokens[1]); 
					} 
					if (tokens[0] == "PRIV") 
					{ 
						rtbChatIn.AppendText("Private from "); 
						rtbChatIn.AppendText(tokens[1].Trim() ); 
						rtbChatIn.AppendText(tokens[2] + "\r\n"); 
					} 
					if (tokens[0] == "JOIN") 
					{ 
						rtbChatIn.AppendText(tokens[1].Trim() ); 
						rtbChatIn.AppendText(" has joined the Chat\r\n"); 
						string newguy = tokens[1].Trim(new char[]{'\r','\n'}); 
						lbChatters.Items.Add(newguy); 
						this.label1.Text = newguy;
					} 
					if (tokens[0] == "GONE") 
					{ 
						rtbChatIn.AppendText(tokens[1].Trim() ); 
						rtbChatIn.AppendText(" has left the Chat\r\n"); 
						lbChatters.Items.Remove(tokens[1].Trim(new char[]{'\r','\n'})); 
					} 
					if (tokens[0] == "QUIT") 
					{ 
						ns.Close(); 
						clientsocket.Close(); 
						keepalive = false; 
						statusBar1.Text = "服务器端已停止"; 
						connected= false; 
						btnSend.Enabled = false; 
						btnDisconnect.Enabled = false; 
					} 
				} 
				catch(Exception){} 
			} 
		}  
		private void QuitChat() 
		{ 
			if(connected) 
			{ 
				try 
				{ 
					string command = "GONE|" + this.textBox2.Text.ToString(); 
					Byte[] outbytes = System.Text.Encoding.Default.GetBytes(command.ToCharArray()); 
					ns.Write(outbytes,0,outbytes.Length); 
					clientsocket.Close(); 
					this.th.Abort();
					this.th.Join();
				} 
				catch(Exception) 
				{ 
				} 
			} 
			this.lbChatters.Items.Remove(this.textBox1.Text.ToString());
			this.Text = "客户端"; 
			statusBar1.Text = "已断开连接"; 
			this.button1.Enabled = true;
			this.btnDisconnect.Enabled = false;
		}

		private void btnSend_Click(object sender, System.EventArgs e)
		{
			string command = "CHAT|" + clientname + ":" + this.textBox1.Text.ToString().Trim()+ "\n"; 
			Byte[] outbytes = System.Text.Encoding.Default.GetBytes(command.ToCharArray()); 
			ns.Write(outbytes,0,outbytes.Length); 
		}

		private void button1_Click(object sender, System.EventArgs e)
		{
			EstablishConnection();
			this.clientname = this.textBox2.Text.ToString();
			th = new Thread(new ThreadStart(ReceiveChat));//新建一个用于监听的线程
         th.Start();//打开新线程
		}

		private void btnDisconnect_Click(object sender, System.EventArgs e)
		{
			this.QuitChat();
		}

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


	}
}

⌨️ 快捷键说明

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