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

📄 mainform.cs

📁 c#写的网络聊天工具
💻 CS
📖 第 1 页 / 共 2 页
字号:
			this.acceptSocket.Send(array);
		}
		// 0 receive msg
		// 1 file finish
		void MakeSound(int arg)
		{
			if(arg == 0)
			{
				MainForm.PlaySound(@"sounds\msg.wav",IntPtr.Zero,0);
			}
			else
			{
				MainForm.PlaySound(@"sounds\finish.wav",IntPtr.Zero,0);
			}
		}
		
		 
        
		//发送文件
		void SendFile(string fileName)
		{
		    
			FileStream fs = new FileStream(fileName,FileMode.Open,FileAccess.Read);
			BinaryReader br = new BinaryReader(fs);
			int count = 0; 
			do 
			{   
				count = br.Read(fbuffer,0,bufferSize);
				this.acceptSocket.Send(fbuffer,0,count,SocketFlags.None);
			}
			while( count == bufferSize );
			
		 
			
			this.currentMode = UserMode.ChatMode;
			this.Text = "局域网聊天程序 - 连接状态";
			
			MessageBox.Show("文件发送成功: "+this.fileToSend);
			
			br.Close();
			fs.Close();
		}
		
		// _W_S_F  要发送文件过去 后面的字节是 文件名
		// _B_S_F  开始发送文件   后面的字节表示文件大小
		// _R_S_A  同意接受文件
		// _R_S_D  拒绝接受文件
		//发送标志性的信息
		void ValidateTag(string str)
		{
			str = str.Trim((char)0);
			string	tag = str.Substring(0,6); 
			string file = str.Substring(6,str.Length-6);
		   
			switch(tag)
			{
				case "_W_S_F":
					
					if(DialogResult.Yes == MessageBox.Show("接收文件吗?","文件传送",MessageBoxButtons.YesNo,MessageBoxIcon.Information))
					{
						this.saveFileDialog.FileName = file;
						if(DialogResult.OK == this.saveFileDialog.ShowDialog())
						{   
							this.fileToSend = this.saveFileDialog.FileName;
							this.SendTagMessage("_R_S_A");
							this.Text = "文件传送中.....";
							this.bytesWriten = 0;
						}
						else
						{
							this.SendTagMessage("_R_S_D");
						}
					}
					break;
				case "_B_S_F":
					this.fileSize = int.Parse(file);
					this.currentMode = UserMode.FileMode;
					this.CanWirterFile = true;
					break;	 
				case "_R_S_A":
					this.Text = "文件传送中.....";
					this.currentMode = UserMode.FileMode;
					this.SendTagMessage("_B_S_F"+this.fileSize.ToString());
					this.asynSendFile = new AsyncCallback(this.EndCall);
					this.sendFileDelegate = new MessageHandler(this.SendFile);
					this.sendFileDelegate.BeginInvoke(this.fileToSend,this.asynSendFile,(object)"d");
					break;
				case "_R_S_D": 
					MessageBox.Show("对方拒绝接受或连接有问题!");
					break;
				default :
					MessageBox.Show("Invalid Message: "+tag);
					break;
			}

		}
		//清空缓存区
		void ClearBuffer()
		{
			for(int i=0; i<512; i++)
			{
				mbuffer[i] = 0;
			}
			for(int j=0; j<bufferSize; j++)
			{
				this.fbuffer[j] = 0;
			}
		}
		//获得数据函数
		void GetMessage()
		{
			this.Text = "局域网聊天程序 - 连接状态";
			while(this.acceptSocket.Connected == true && !this.Disposing)
			{
				try
				{
					int count = 0;
					string tag ="";
					
					if(this.currentMode == UserMode.ChatMode)
					{
						count = this.acceptSocket.Receive(this.mbuffer);
						tag = System.Text.Encoding.UTF7.GetString(mbuffer,0,count);
					}
					else
					{
						count = this.acceptSocket.Receive(this.fbuffer);
						tag = System.Text.Encoding.UTF7.GetString(fbuffer,0,count);
					}
					
					if( tag.Substring(0,1).Equals("_")&&
						tag.Substring(2,1).Equals("_")&&
						tag.Substring(4,1).Equals("_"))
					{ 
						this.ValidateTag(tag);
					}
					else
					{
						//如果是聊天模式
						if(this.currentMode == UserMode.ChatMode)
						{
							this.richMessageBox.Text += tag+"\n";
							this.ClearBuffer();
							this.MakeSound(0);
						}
						else //文件传输模式 
						{
							if(this.CanWirterFile)
							{
								 
								if(!File.Exists(this.fileToSend))
								{
									StreamWriter sw = new StreamWriter(this.fileToSend,false);
									sw.Close();
								}
								FileStream fs = new FileStream(this.fileToSend,FileMode.Append,FileAccess.Write);
								BinaryWriter br = new BinaryWriter(fs);
								br.Write(this.fbuffer,0,count);
								this.bytesWriten += count;  //累计已经写下的字节数
								br.Close();
								fs.Close();
								this.ClearBuffer();
								  
								if(this.bytesWriten == this.fileSize)  //一致完成
								{
									this.fileSize = 0;
									this.currentMode = UserMode.ChatMode;
									this.Text = "局域网聊天程序 - 连接状态";
									this.ClearBuffer();
									this.MakeSound(1);
									MessageBox.Show("文件已经保存到: "+this.fileToSend);
								}
								else
								{
									if(this.bytesWriten > this.fileSize) //实际传送的大于原文件
									{
									
										MessageBox.Show("文件传送过程中发生错误!");
									}
								
								}
							}
						}
					}
					
				}
				catch(Exception e)
				{
					this.CloseAll();
					MessageBox.Show(e.Message);
					return ;
				}
			}
		}
		//发送消息
		void SendMessage(string str)
		{
			if(this.currentMode == UserMode.FileMode)
			{
				return ;
			}
			
			if(this.acceptSocket != null)
			{
				if(String.Empty != str)
				{
					string info = System.DateTime.Now.ToShortTimeString()+" 用户: "+this.txUserName.Text+"\n";
					info += str;
					info += "\n";
					byte[] buffer = System.Text.UTF7Encoding.UTF7.GetBytes(info);
					this.acceptSocket.Send(buffer);
					
					this.richMessageBox.Text += info;
					this.txtInput.Clear(); 
				}
			}
			else
			{
				MessageBox.Show("未连接状态!");
			}
		}

		 

		private void Form1_Closed(object sender, System.EventArgs e)
		{
			this.CloseAll();
		}
		//更新RICHTEXTBOX防止数据超出范围
		private void richMessageBox_TextChanged(object sender, System.EventArgs e)
		{
			if(this.richMessageBox.Text.Length > 1000)
			{
				this.richMessageBox.Text.Remove(0,500);
			}
			this.richMessageBox.Select(this.richMessageBox.TextLength-1,0);     
		}

		//尝试连接
		private void TryToConnect()
		{
			this.btnConnect.Enabled = false;
			this.btnCreate.Enabled = false;
			this.Text = "尝试连接到: "+this.txtIp.Text+"  端口: "+this.txtPort.Text;
			try
			{
				this.acceptSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
				IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(this.txtIp.Text),int.Parse(this.txtPort.Text));
				this.acceptSocket.Connect(ipe);
			        
				this.btnClose.Enabled = true;
				this.btnCreate.Enabled = false;
				this.btnSend.Enabled = true;
				this.btnConnect.Enabled = false;
				   
				this.IsConnected = true;   
				this.netDelegate = new NetDelegate(this.GetMessage);
				this.asynCallDelegate = new AsyncCallback(this.EndCall);
				this.netDelegate.BeginInvoke(this.asynCallDelegate,(object)"ddd"); 
			}
			catch(Exception e)
			{
				this.CloseAll();
				MessageBox.Show(e.Message);
				return ;
			}
		}
		 
		//关闭所有
		void CloseAll()
		{
			if( this.mainSocket!=null )
			{
				this.mainSocket.Close();
				this.mainSocket = null;
			}
			if( this.acceptSocket != null)
			{
				this.acceptSocket.Close();
				this.acceptSocket = null;
			}
			this.btnClose.Enabled = false;
			this.btnSend.Enabled = false;
			this.btnCreate.Enabled = true;
			this.btnConnect.Enabled = true;
			this.Text = "局域网聊天程序 - 断开状态";
			this.IsConnected = false;
		}
		//创建
		private void btnCreate_Click(object sender, System.EventArgs e)
		{
			this.BeginListen();
		}
		//连接 
		private void btnConnect_Click(object sender, System.EventArgs e)
		{
			this.TryToConnect();
		}
		//发送消息
		private void btnSend_Click(object sender, System.EventArgs e)
		{
			this.SendMessage(this.txtInput.Text);
		}
		//断开连接
		private void btnClose_Click(object sender, System.EventArgs e)
		{
			this.CloseAll();
		}
		//传送文件
		private void mmiSendFile_Click(object sender, System.EventArgs e)
		{   
			if(!this.IsConnected) 
			{
				MessageBox.Show("非连接状态不能发送文件!");
				return;
			}
			if(UserMode.FileMode == this.currentMode)
			{
				return;
			}
			
			if(DialogResult.OK == this.openFileDialog.ShowDialog())
			{   
			   
				this.fileToSend = this.openFileDialog.FileName;
				string []file = this.fileToSend.Split(Path.DirectorySeparatorChar);
				this.SendTagMessage("_W_S_F"+file[file.Length-1]);  //发送标志 和 文件名
				FileStream fs = new FileStream(this.openFileDialog.FileName,FileMode.Open,FileAccess.Read);
				this.fileSize = (int)fs.Length;
				fs.Close();
			} 
		 
		}

		private void menuItem3_Click(object sender, System.EventArgs e)
		{
	
		}
	}
}

⌨️ 快捷键说明

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