C#聊天,C#简易聊天室

ChatRoom_Server


/*
 * 由SharpDevelop创建。
 * 用户: HBshuai
 * 日期: 2015/12/17 星期四
 * 时间: 23:34
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net; //IP,IPAdress(port)
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace ChatRoom_Server
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			//关闭对文本框跨线程操作的检查
			TextBox.CheckForIllegalCrossThreadCalls = false;
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}

        Thread threadWatch = null;//负责监听客户端请求的线程
        Socket socketWatch = null;//负责监听服务端的套接字


        //Socket socketConnection = null;//负责和客户端通信的套接字
        //保存了服务器端所有和客户端通信的套接字
        Dictionary<string, Socket> dict = new Dictionary<string, Socket>();

        //保存了服务器端所有负责调用通信套接字的Receive方法的线程
        Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();

        //开启服务
		void BtnBeginListenClick(object sender, EventArgs e)
		{
            //创建负责监听的套接字,参数使用IP4寻址协议,使用流式连接,使用TCP协议传输数据
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获得文本框中的IP地址对象
            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
            //创建包含IP和port的网络节点对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
            //将负责监听的套接字绑定到唯一的IP和端口上
            try
            {
                socketWatch.Bind(endpoint);
            }
            catch (SocketException ex)
            {
                ShowMsg("绑定IP时出现异常:" + ex.Message);
                return;
            }
            catch (Exception ex)
            {
                ShowMsg("绑定IP时出现异常:" + ex.Message);
                return;
            }

            //设置监听队列的长度
            socketWatch.Listen(10);

            //创建负责监听的线程,并传入监听方法
            threadWatch = new Thread(WatchConnection);
            threadWatch.IsBackground = true;//设置为后台线程
            threadWatch.Start();//开启线程

            ShowMsg("服务端启动监听成功~");
		}
		
		//发送消息到客户端
		void BtnSendClick(object sender, EventArgs e)
		{
            if (string.IsNullOrEmpty(lbOnline.Text))
            {
                MessageBox.Show("请选择要发送的好友.");
            }
            else
            {
                string strMsg = txtMsgSend.Text.Trim();
                //将要发送的字符串转成UTF-8对应的字节数组
                byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);

                //获得列表中选中的远程IP的Key
                string strClientKey = lbOnline.Text;
                try
                {
                    //通过key找到字典集合中对应的某个客户端通信的套接字,用Send方法发送数据给对方
                    dict[strClientKey].Send(arrMsg);

                    ShowMsg(string.Format("我对 {0} 说: {1}", strClientKey, strMsg));
                    //清空发送框中的消息
                    this.txtMsgSend.Text = "";
                }
                catch (SocketException ex)
                {
                    ShowMsg("发送时出现异常:" + ex.Message);
                }
                catch (Exception ex)
                {
                    ShowMsg("发送时出现异常:" + ex.Message);
                }                
            }
		}
		
        //群发消息给每个客户端
		void BtnSendToAllClick(object sender, EventArgs e)
		{
            string strMsg = txtMsgSend.Text.Trim();
            //将要发送的消息转成utf8对应的字节数组
            byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);
            foreach (Socket s in dict.Values)
            {
                try
                {
                    s.Send(arrMsg);
                    ShowMsg("群发完毕!");
                }
                catch (SocketException e)
                {
                    ShowMsg("服务端群发时出现异常:" + e.Message);
                    break;
                }
                catch (Exception e)
                {
                    ShowMsg("服务端群发时出现异常:" + e.Message);
                    break;
                }
            }  
		}


        /// <summary>
        /// 监听客户端请求的方法
        /// </summary>
        void WatchConnection()
        {
            //持续不断的监听客户端的新的连接请求
            while (true)
            {
                Socket socketConnection = null;
                try
                {
                    //开始监听请求,返回一个新的负责连接的套接字,负责和该客户端通信
                    //注意:Accept方法会阻断当前线程!
                    socketConnection = socketWatch.Accept();
                }
                catch (SocketException ex)
                {
                    ShowMsg("服务端连接时发生异常:" + ex.Message);
                    break;
                }
                catch (Exception ex)
                {
                    ShowMsg("服务端连接时发生异常:" + ex.Message);
                    break;
                }

                //当有新的socket连接到服务端时就将IP添加到在线列表中,作为客户端的唯一标识                
                lbOnline.Items.Add(socketConnection.RemoteEndPoint.ToString());

                //将每个新产生的套接字存起来,装到键值对Dict集合中,以客户端IP:端口作为key
                dict.Add(socketConnection.RemoteEndPoint.ToString(), socketConnection);

                //为每个服务端通信套接字创建一个单独的通信线程,负责调用通信套接字的Receive方法,监听客户端发来的数据
                //创建通信线程
                Thread threadCommunicate = new Thread(ReceiveMsg);
                threadCommunicate.IsBackground = true;
                threadCommunicate.Start(socketConnection);//有传入参数的线程

                dictThread.Add(socketConnection.RemoteEndPoint.ToString(), threadCommunicate);

                ShowMsg(string.Format("{0} 上线了. ", socketConnection.RemoteEndPoint.ToString()));
            }
        }

        /// <summary>
        /// 服务端监听客户端发来的数据
        /// </summary>
        void ReceiveMsg(object socketClientPara)
        {
            Socket socketClient = socketClientPara as Socket;
            while (true)
            {
                //定义一个接收消息用的字节数组缓冲区(2M大小)
                byte[] arrMsgRev = new byte[1024 * 1024 * 2];
                //将接收到的数据存入arrMsgRev,并返回真正接收到数据的长度
                int length = -1;
                try
                {
                    length = socketClient.Receive(arrMsgRev);
                }
                catch (SocketException ex)
                {
                    ShowMsg("异常:" + ex.Message+", RemoteEndPoint: "+socketClient.RemoteEndPoint.ToString());
                    //从通信套接字结合中删除被中断连接的通信套接字
                    dict.Remove(socketClient.RemoteEndPoint.ToString());
                    //从通信线程集合中删除被中断连接的通信线程对象
                    dictThread.Remove(socketClient.RemoteEndPoint.ToString());
                    //从显示列表中移除被中断连接的IP:Port
                    lbOnline.Items.Remove(socketClient.RemoteEndPoint.ToString());
                    break;
                }
                catch (Exception ex)
                {
                    ShowMsg("异常:" + ex.Message);
                    break;
                }
                if (arrMsgRev[0] == 0) //判断客户端发送过来数据的第一位元素是0,代表文字
                {
                    //此时是将数组的所有元素(每个字节)都转成字符串,而真正接收到只有服务端发来的几个字符
                    string strMsgReceive = Encoding.UTF8.GetString(arrMsgRev, 1, length - 1);
                    ShowMsg(string.Format("{0} 对我说:{1}", socketClient.RemoteEndPoint.ToString(), strMsgReceive));
                }
                else if (arrMsgRev[0] == 1)//1代表文件
                {
                    //保存文件对话框对象
                    SaveFileDialog sfd = new SaveFileDialog();
                    //*****此处很重要,由于线程安全原因,必须加上this才能打开对话框,切记~!!浪费2个小时!!!
                    if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                    {
                        //获取文件将要保存的路径
                        string fileSavePath = sfd.FileName;
                        //创建文件流,让文件流根据路径创建一个文件
                        using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
                        {
                            fs.Write(arrMsgRev, 1, length - 1);
                            ShowMsg("文件保存成功: " + fileSavePath);
                        }
                    }

                }
            }
        }

        void ShowMsg(string msg)
        {
            txtMsg.AppendText(msg + "\n");
        }
        
        
	}
}
/*
 * 由SharpDevelop创建。
 * 用户: HBshuai
 * 日期: 2015/12/17 星期四
 * 时间: 23:34
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
namespace ChatRoom_Server
{
	partial class MainForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox txtIP;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtPort;
		private System.Windows.Forms.Button btnBeginListen;
		private System.Windows.Forms.TextBox txtMsg;
		private System.Windows.Forms.TextBox txtMsgSend;
		private System.Windows.Forms.Button btnSend;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ListBox lbOnline;
		private System.Windows.Forms.Button btnSendToAll;
		
		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}
		
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			this.label1 = new System.Windows.Forms.Label();
			this.txtIP = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.txtPort = new System.Windows.Forms.TextBox();
			this.btnBeginListen = new System.Windows.Forms.Button();
			this.txtMsg = new System.Windows.Forms.TextBox();
			this.txtMsgSend = new System.Windows.Forms.TextBox();
			this.btnSend = new System.Windows.Forms.Button();
			this.label3 = new System.Windows.Forms.Label();
			this.lbOnline = new System.Windows.Forms.ListBox();
			this.btnSendToAll = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// label1
			// 
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(25, 31);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(23, 12);
			this.label1.TabIndex = 0;
			this.label1.Text = "IP:";
			// 
			// txtIP
			// 
			this.txtIP.Location = new System.Drawing.Point(85, 21);
			this.txtIP.Name = "txtIP";
			this.txtIP.Size = new System.Drawing.Size(100, 21);
			this.txtIP.TabIndex = 1;
			this.txtIP.Text = "127.0.0.1";
			// 
			// label2
			// 
			this.label2.AutoSize = true;
			this.label2.Location = new System.Drawing.Point(207, 31);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(35, 12);
			this.label2.TabIndex = 0;
			this.label2.Text = "Port:";
			// 
			// txtPort
			// 
			this.txtPort.Location = new System.Drawing.Point(267, 21);
			this.txtPort.Name = "txtPort";
			this.txtPort.Size = new System.Drawing.Size(100, 21);
			this.txtPort.TabIndex = 1;
			this.txtPort.Text = "4351";
			// 
			// btnBeginListen
			// 
			this.btnBeginListen.Location = new System.Drawing.Point(452, 19);
			this.btnBeginListen.Name = "btnBeginListen";
			this.btnBeginListen.Size = new System.Drawing.Size(75, 23);
			this.btnBeginListen.TabIndex = 2;
			this.btnBeginListen.Text = "开启服务";
			this.btnBeginListen.UseVisualStyleBackColor = true;
			this.btnBeginListen.Click += new System.EventHandler(this.BtnBeginListenClick);
			// 
			// txtMsg
			// 
			this.txtMsg.Location = new System.Drawing.Point(183, 77);
			this.txtMsg.Multiline = true;
			this.txtMsg.Name = "txtMsg";
			this.txtMsg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.txtMsg.Size = new System.Drawing.Size(344, 174);
			this.txtMsg.TabIndex = 3;
			// 
			// txtMsgSend
			// 
			this.txtMsgSend.Location = new System.Drawing.Point(183, 293);
			this.txtMsgSend.Name = "txtMsgSend";
			this.txtMsgSend.Size = new System.Drawing.Size(344, 21);
			this.txtMsgSend.TabIndex = 4;
			// 
			// btnSend
			// 
			this.btnSend.Location = new System.Drawing.Point(452, 320);
			this.btnSend.Name = "btnSend";
			this.btnSend.Size = new System.Drawing.Size(75, 23);
			this.btnSend.TabIndex = 5;
			this.btnSend.Text = "发送消息";
			this.btnSend.UseVisualStyleBackColor = true;
			this.btnSend.Click += new System.EventHandler(this.BtnSendClick);
			// 
			// label3
			// 
			this.label3.AutoSize = true;
			this.label3.Location = new System.Drawing.Point(27, 77);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(65, 12);
			this.label3.TabIndex = 6;
			this.label3.Text = "在线列表:";
			// 
			// lbOnline
			// 
			this.lbOnline.FormattingEnabled = true;
			this.lbOnline.ItemHeight = 12;
			this.lbOnline.Location = new System.Drawing.Point(29, 102);
			this.lbOnline.Name = "lbOnline";
			this.lbOnline.Size = new System.Drawing.Size(130, 208);
			this.lbOnline.TabIndex = 7;
			// 
			// btnSendToAll
			// 
			this.btnSendToAll.Location = new System.Drawing.Point(452, 353);
			this.btnSendToAll.Name = "btnSendToAll";
			this.btnSendToAll.Size = new System.Drawing.Size(75, 23);
			this.btnSendToAll.TabIndex = 5;
			this.btnSendToAll.Text = "群发消息";
			this.btnSendToAll.UseVisualStyleBackColor = true;
			this.btnSendToAll.Click += new System.EventHandler(this.BtnSendToAllClick);
			// 
			// MainForm
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(589, 399);
			this.Controls.Add(this.btnSendToAll);
			this.Controls.Add(this.lbOnline);
			this.Controls.Add(this.label3);
			this.Controls.Add(this.btnSend);
			this.Controls.Add(this.txtMsgSend);
			this.Controls.Add(this.txtMsg);
			this.Controls.Add(this.btnBeginListen);
			this.Controls.Add(this.txtPort);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.txtIP);
			this.Controls.Add(this.label1);
			this.Name = "MainForm";
			this.Text = "聊天程序服务端";
			this.ResumeLayout(false);
			this.PerformLayout();

		}
	}
}

ChatRoom_Client


/*
 * 由SharpDevelop创建。
 * 用户: HBshuai
 * 日期: 2015/12/18 星期五
 * 时间: 0:24
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;


namespace ChatRoom_Client
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		//客户端负责接收服务端发来的数据消息的线程
        Thread threadClient = null;
        //创建客户端套接字,负责连接服务器
        Socket socketClient = null;

		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			//关闭对文本框跨线程操作的检查
            TextBox.CheckForIllegalCrossThreadCalls = false;
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
        //连接服务器
		void BtnConnectClick(object sender, EventArgs e)
		{
            //获得文本框中的IP地址对象
            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
            //创建包含IP和端口的网络节点对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
            //创建客户端套接字,负责连接服务器
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                //客户端连接到服务器
                socketClient.Connect(endpoint);
            }
            catch (SocketException ex)
            {
                ShowMsg("客户端连接服务器发生异常:" + ex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg("客户端连接服务器发生异常:" + ex.Message);
            }

            threadClient = new Thread(ReceiveMsg);
            threadClient.IsBackground = true;
            threadClient.Start();
		}
		//向服务器发送文本消息
		void BtnSendMsgClick(object sender, EventArgs e)
		{
            string strMsg = txtMsgSend.Text.Trim();
            //将字符串转成方便网络传送的二进制数组
            byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);
            byte[] arrMsgSend = new byte[arrMsg.Length + 1];
            arrMsgSend[0] = 0;//设置标识位,0代表发送的是文字
            Buffer.BlockCopy(arrMsg, 0, arrMsgSend, 1, arrMsg.Length);
            try
            {
                socketClient.Send(arrMsgSend);

                ShowMsg(string.Format("我对 {0} 说:{1}", socketClient.RemoteEndPoint.ToString(), strMsg));
                //清空发送消息文本框中的消息
                this.txtMsgSend.Text = "";
            }
            catch (SocketException ex)
            {
                ShowMsg("客户端发送消息时发生异常:" + ex.Message);
            }
            catch (Exception ex)
            {
                ShowMsg("客户端发送消息时发生异常:" + ex.Message);
            }
		}
		
		void BtnChooseFileClick(object sender, EventArgs e)
		{
			//选择要发送的文件
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFilePath.Text = ofd.FileName;
            }
		}
		//客户端向服务器发送文件
		void BtnSendFileClick(object sender, EventArgs e)
		{
            //用文件流打开用户选择的文件
            using (FileStream fs = new FileStream(txtFilePath.Text, FileMode.Open))
            {
                //定义一个4M的数组(缓冲区)
                byte[] arrFile = new byte[1024 * 1024 * 2];
                //将文件数据读到数组arrFile中,并获取文件的真实长度
                int length = fs.Read(arrFile, 0, arrFile.Length);
                //用于发送真实数据的数组,多了一位标识位
                byte[] arrFileSend = new byte[length + 1];
                //第一位是协议位,1:文件 0:文字
                arrFileSend[0] = 1;
                //for (int i = 0; i < length; i++) //将数据拷贝到真实数组中
                //{
                //    arrFileSend[i + 1] = arrFile[i];
                //}
                //2.直接拷贝,不能指定其实元素位置offset
                //arrFile.CopyTo(arrFileSend, length);
                //3.
                Buffer.BlockCopy(arrFile, 0, arrFileSend, 1, length);
                //发送包含了标识位的新数据数组到服务端
                socketClient.Send(arrFileSend);
            }
		}

        void ShowMsg(string msg)
        {
            txtMsg.AppendText(msg + "\r\n");
        }

        /// <summary>
        /// 监听服务端发来的消息
        /// </summary>
        void ReceiveMsg()
        {
            while (true)
            {
                //定义一个接收消息用的字节数组缓冲区(2M大小)
                byte[] arrMsgRev = new byte[1024 * 1024 * 2];
                //将接收到的数据存入arrMsgRev,并返回真正接收到数据的长度
                int length = -1;
                try
                {
                    length = socketClient.Receive(arrMsgRev);
                }
                catch (SocketException ex)
                {
                    ShowMsg("客户端接收消息时发生异常:" + ex.Message);
                    break;
                }
                catch (Exception ex)
                {
                    ShowMsg("客户端接收消息时发生异常:" + ex.Message);
                    break;
                }

                //此时是将数组的所有元素(每个字节)都转成字符串,而真正接收到只有服务端发来的几个字符
                string strMsgReceive = Encoding.UTF8.GetString(arrMsgRev, 0, length);
                ShowMsg(string.Format("{0} 对我说:{1}", socketClient.RemoteEndPoint.ToString(), strMsgReceive));
            }
        }
        
	}
}

/*
 * 由SharpDevelop创建。
 * 用户: HBshuai
 * 日期: 2015/12/18 星期五
 * 时间: 0:24
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
namespace ChatRoom_Client
{
	partial class MainForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;
		private System.Windows.Forms.Button btnConnect;
		private System.Windows.Forms.TextBox txtPort;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.TextBox txtIP;
		private System.Windows.Forms.TextBox txtMsg;
		private System.Windows.Forms.Button btnSendMsg;
		private System.Windows.Forms.TextBox txtMsgSend;
		private System.Windows.Forms.Button btnSendFile;
		private System.Windows.Forms.TextBox txtFilePath;
		private System.Windows.Forms.Button btnChooseFile;
		
		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}
		
		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnConnect = new System.Windows.Forms.Button();
			this.txtPort = new System.Windows.Forms.TextBox();
			this.label1 = new System.Windows.Forms.Label();
			this.label2 = new System.Windows.Forms.Label();
			this.txtIP = new System.Windows.Forms.TextBox();
			this.txtMsg = new System.Windows.Forms.TextBox();
			this.btnSendMsg = new System.Windows.Forms.Button();
			this.txtMsgSend = new System.Windows.Forms.TextBox();
			this.btnSendFile = new System.Windows.Forms.Button();
			this.txtFilePath = new System.Windows.Forms.TextBox();
			this.btnChooseFile = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// btnConnect
			// 
			this.btnConnect.Location = new System.Drawing.Point(464, 20);
			this.btnConnect.Name = "btnConnect";
			this.btnConnect.Size = new System.Drawing.Size(75, 23);
			this.btnConnect.TabIndex = 7;
			this.btnConnect.Text = "连接服务器";
			this.btnConnect.UseVisualStyleBackColor = true;
			this.btnConnect.Click += new System.EventHandler(this.BtnConnectClick);
			// 
			// txtPort
			// 
			this.txtPort.Location = new System.Drawing.Point(279, 22);
			this.txtPort.Name = "txtPort";
			this.txtPort.Size = new System.Drawing.Size(100, 21);
			this.txtPort.TabIndex = 5;
			this.txtPort.Text = "4351";
			// 
			// label1
			// 
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(37, 32);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(23, 12);
			this.label1.TabIndex = 4;
			this.label1.Text = "IP:";
			// 
			// label2
			// 
			this.label2.AutoSize = true;
			this.label2.Location = new System.Drawing.Point(219, 32);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(35, 12);
			this.label2.TabIndex = 3;
			this.label2.Text = "Port:";
			// 
			// txtIP
			// 
			this.txtIP.Location = new System.Drawing.Point(97, 22);
			this.txtIP.Name = "txtIP";
			this.txtIP.Size = new System.Drawing.Size(100, 21);
			this.txtIP.TabIndex = 6;
			this.txtIP.Text = "127.0.0.1";
			// 
			// txtMsg
			// 
			this.txtMsg.Location = new System.Drawing.Point(97, 68);
			this.txtMsg.Multiline = true;
			this.txtMsg.Name = "txtMsg";
			this.txtMsg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
			this.txtMsg.Size = new System.Drawing.Size(442, 211);
			this.txtMsg.TabIndex = 8;
			// 
			// btnSendMsg
			// 
			this.btnSendMsg.Location = new System.Drawing.Point(464, 304);
			this.btnSendMsg.Name = "btnSendMsg";
			this.btnSendMsg.Size = new System.Drawing.Size(75, 23);
			this.btnSendMsg.TabIndex = 10;
			this.btnSendMsg.Text = "发送消息";
			this.btnSendMsg.UseVisualStyleBackColor = true;
			this.btnSendMsg.Click += new System.EventHandler(this.BtnSendMsgClick);
			// 
			// txtMsgSend
			// 
			this.txtMsgSend.Location = new System.Drawing.Point(97, 304);
			this.txtMsgSend.Name = "txtMsgSend";
			this.txtMsgSend.Size = new System.Drawing.Size(335, 21);
			this.txtMsgSend.TabIndex = 9;
			// 
			// btnSendFile
			// 
			this.btnSendFile.Location = new System.Drawing.Point(464, 345);
			this.btnSendFile.Name = "btnSendFile";
			this.btnSendFile.Size = new System.Drawing.Size(75, 23);
			this.btnSendFile.TabIndex = 12;
			this.btnSendFile.Text = "发送文件";
			this.btnSendFile.UseVisualStyleBackColor = true;
			this.btnSendFile.Click += new System.EventHandler(this.BtnSendFileClick);
			// 
			// txtFilePath
			// 
			this.txtFilePath.BackColor = System.Drawing.Color.White;
			this.txtFilePath.Location = new System.Drawing.Point(97, 347);
			this.txtFilePath.Name = "txtFilePath";
			this.txtFilePath.ReadOnly = true;
			this.txtFilePath.Size = new System.Drawing.Size(268, 21);
			this.txtFilePath.TabIndex = 11;
			// 
			// btnChooseFile
			// 
			this.btnChooseFile.Location = new System.Drawing.Point(374, 345);
			this.btnChooseFile.Name = "btnChooseFile";
			this.btnChooseFile.Size = new System.Drawing.Size(75, 23);
			this.btnChooseFile.TabIndex = 13;
			this.btnChooseFile.Text = "选择文件";
			this.btnChooseFile.UseVisualStyleBackColor = true;
			this.btnChooseFile.Click += new System.EventHandler(this.BtnChooseFileClick);
			// 
			// MainForm
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(626, 399);
			this.Controls.Add(this.btnChooseFile);
			this.Controls.Add(this.txtFilePath);
			this.Controls.Add(this.btnSendFile);
			this.Controls.Add(this.txtMsgSend);
			this.Controls.Add(this.btnSendMsg);
			this.Controls.Add(this.txtMsg);
			this.Controls.Add(this.txtIP);
			this.Controls.Add(this.label2);
			this.Controls.Add(this.label1);
			this.Controls.Add(this.txtPort);
			this.Controls.Add(this.btnConnect);
			this.Name = "MainForm";
			this.Text = "聊天程序客户端";
			this.ResumeLayout(false);
			this.PerformLayout();

		}
	}
}


  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要实现C#简易聊天室,可以使用Socket来进行操作。首先,声明一个套接字(Socket)作为监听套接字,使用AddressFamily.InterNetwork、SocketType.Stream和ProtocolType.Tcp来创建这个套接字。接下来,需要设置服务器的IP地址和端口号。然后,使用Socket的Bind方法将套接字绑定到指定的IP地址和端口上。接着,使用Socket的Listen方法开始监听连接请求。当有客户端连接请求时,可以使用Accept方法接受连接,并创建一个新的套接字来处理该连接。这样就可以与客户端进行通信了。 在聊天室中,可以使用多线程来处理多个客户端的连接。当有新的客户端连接时,创建一个新的线程来处理该连接,这样就可以同时处理多个客户端的消息收发。 在处理客户端消息的过程中,可以使用Socket的Receive和Send方法来接收和发送数据。可以使用StreamReader和StreamWriter类来简化数据的读取和写入操作。 通过这些步骤,就可以实现一个简单C# Socket聊天室。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C#基于Socket的简单聊天室实践](https://blog.csdn.net/wyqlxy/article/details/46923611)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值