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

📄 form1.cs

📁 网络聊天,写的比较简单,但比较容易看懂,别的就不用说了吧
💻 CS
📖 第 1 页 / 共 2 页
字号:
			Application.Run(new Form1());
		}

		private void Form1_Load(object sender, System.EventArgs e)
		{
			
			//InitSocket(ref mySoc);
		}

		public void startListen()
		{
			int nPort = Convert.ToInt32(txtPort.Text);
			
			IPEndPoint ipLocalEndPoint;
			try
			{
				IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
				ipLocalEndPoint = new IPEndPoint(ipAddress, nPort); //Listen at Port 999
			}
			catch(SocketException socErr )
			{
				label1.Text=socErr.Message;
				return;
			}
           
			try
			{
				ListenSoc = new WSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp );
				ListenSoc.Soc.Bind(ipLocalEndPoint);
				ListenSoc.Soc.Listen(100);
				while (true)
				{
					allDone.Reset();
					ListenSoc.Soc.BeginAccept(new AsyncCallback(AcceptCallback),ListenSoc);
					allDone.WaitOne();

				}

			}
			catch(Exception err) 
			{
				label1.Text =err.Message;
			}
		}

		public void AcceptCallback(IAsyncResult ar) 
		{
			try
			{
				allDone.Set();
				WSocket listener = (WSocket) ar.AsyncState;
				int nSoc = GetAvailbleSocket();
				SocClient[nSoc].Soc = (Socket)ListenSoc.Soc.EndAccept(ar);
				
				SocClient[nSoc].SockRefNo = nSocRef;
				SocClient[nSoc].RemoteUserName = txtIP.Text;
				SocClient[nSoc].OnConnected += new ConnectDelegate(OnConnected);
				SocClient[nSoc].OnDisconnected += new DisconnectDelegate(OnDisconnected);
				SocClient[nSoc].OnReadyReceive += new ReceiveDelegate(OnReceive);
				SocClient[nSoc].OnReadySend += new SendDelegate(OnReadySend);
				SocClient[nSoc].OnConnectClose += new CloseDelegate(OnCloseRemote);
                SocClient[nSoc].OnSockMessage += new MessageDelegate(OnSockMessage);
				SocClient[nSoc].OnSendingFile += new  SendingDelegate(OnSending);
                SocClient[nSoc].OnReceiveFile += new RecvFileDelegate(OnSending);

				SocClient[nSoc].ReceiveData();  
				ListViewItem item = new ListViewItem();
				item.Text = nSoc.ToString();
				item.SubItems.Add(SocClient[nSoc].Soc.RemoteEndPoint.ToString());
				item.SubItems.Add(txtIP.Text);
			  
				listView1.Items.Add(item);

			}
			catch(Exception err) 
			{
				
				label1.Text ="Accept :"+ err.Message +err.Source.ToString();
			}
		}



		private void InitSocket(ref WSocket Soc,int nSocRef)
		{
			try
			{
				Soc = new WSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp );
				Soc.SockRefNo = nSocRef;
				Soc.RemoteUserName = txtIP.Text;
				Soc.OnConnected += new ConnectDelegate(OnConnected);
				Soc.OnDisconnected += new DisconnectDelegate(OnDisconnected);
				Soc.OnReadyReceive += new ReceiveDelegate(OnReceive);
				Soc.OnReadySend += new SendDelegate(OnReadySend);
				Soc.OnConnectClose += new CloseDelegate(OnCloseRemote);
				Soc.OnSocketError += new SockErrDelegate(OnSocketError);
				Soc.OnSockMessage += new MessageDelegate(OnSockMessage);
				Soc.OnSendingFile += new SendingDelegate(OnSending);
				Soc.OnReceiveFile += new RecvFileDelegate(OnSending);
			}
			catch(Exception err) 
			{
				label1.Text =err.Message;
			}
		}

		private void RomoveSocEvent(ref WSocket Soc)
		{
			try
			{
				Soc.OnConnected -= new ConnectDelegate(OnConnected);
				Soc.OnDisconnected -= new DisconnectDelegate(OnDisconnected);
				Soc.OnReadyReceive -= new ReceiveDelegate(OnReceive);
				Soc.OnReadySend -= new SendDelegate(OnReadySend);
				Soc.OnConnectClose -= new CloseDelegate(OnCloseRemote);
				Soc.OnSocketError -= new SockErrDelegate(OnSocketError);
				Soc.OnSockMessage -= new MessageDelegate(OnSockMessage);
				Soc.OnSendingFile -= new SendingDelegate(OnSending);
				Soc.OnReceiveFile -= new RecvFileDelegate(OnSending);
			}
			catch(Exception err) 
			{
				label1.Text =err.Message;
			}
		}
        
		private void button1_Click(object sender, System.EventArgs e)
		{
			int nPort = Convert.ToInt32(txtCPort.Text);
			IPEndPoint ipLocalEndPoint;
			try
			{
				IPAddress ipAddress = Dns.Resolve(txtIP.Text.ToString()).AddressList[0];
				ipLocalEndPoint = new IPEndPoint(ipAddress, nPort);
			}
			catch(SocketException socErr )
			{
				MessageBox.Show(socErr.Message);
				return;
			}
            int nSoc = GetAvailbleSocket();
            try
			{  
				
			    SocClient[nSoc].SockRefNo = nSoc;	
				if (SocClient[nSoc]==null)
					InitSocket(ref SocClient[nSoc],nSoc);

				if (!SocClient[nSoc].Soc.Connected)
					SocClient[nSoc].AsyConnectTCIP(ipLocalEndPoint);	
			}
			catch (Exception err) 
			{
				label1.Text="Connect Button :"+err.Message;
				InitSocket(ref SocClient[nSoc],nSoc);
			}
		 
		}

		private void OnConnected(object sender, SockEventArgs e)
		{
		   	label1.Text = "Connected";
			SocClient[e.SocketRef].ReceiveData();
			//listBox2.Items.Add(e.SocketRef.ToString()+SocClient[e.SocketRef].RemoteEndPoint.ToString());
			//listView1.Items.Add(
			ListViewItem item = new ListViewItem();
			  item.Text = e.SocketRef.ToString();
			  item.SubItems.Add(SocClient[e.SocketRef].Soc.RemoteEndPoint.ToString());
			  item.SubItems.Add(e.RemoteUserName);
			  
		    listView1.Items.Add(item);
		}

		private void OnDisconnected(object sender, SockEventArgs e)
		{
		    label1.Text = "Disconnected";
			RomoveSocEvent(ref SocClient[e.SocketRef]);
			
			 
		}

		private void OnSending(object sender, SockEventArgs e)
		{   
            double nSize = Convert.ToDouble(e.SockMsg);
			int Val =Convert.ToInt32((e.ByteSend/nSize)*100);
			txtPer.Text = Val.ToString()+" %";
			prgBar.Value= Val;
			//listBox1.Items.Add(e.SockMsg+ " "+e.ByteSend.ToString()+" = "+ Val.ToString() );
		}

		private void OnSockMessage(object sender, SockEventArgs e)
		{
			listBox1.Items.Add(txtIP.Text+" <<"+ e.SockMsg);
		}

		private void OnReceive(object sender, SockEventArgs e)
		{
			
			//listBox1.Items.Add(txtIP.Text+" <<"+ SocClient[e.SocketRef].response.ToString());
			//listBox1.SelectedIndex =listBox1.Items.Count;
			//SocClient[e.SocketRef].response.Remove(0,SocClient[e.SocketRef].response.Length);
		}

		private void OnReadySend(object sender, SockEventArgs e)
		{
			label1.Text = "Ready to send";
		}

		private void OnSocketError(object sender, SockEventArgs e)
		{
			label1.Text = e.SockMsg;
		}

		private void OnCloseRemote(object sender, SockEventArgs e)
		{
			
			label1.Text = "Remote Close";
			nClose +=1;
			txtClose.Text = nClose.ToString();  
			foreach (ListViewItem aa in listView1.Items)
			{
				if (aa.Text == e.SocketRef.ToString())
				{
					listView1.Items.Remove(aa);
					break;
				}
			}
		}

		private void button2_Click(object sender, System.EventArgs e)
		{
			try
			{
				if (mySoc!=null)
				{   
					if (mySoc.Soc.Connected)
						mySoc.DisConnectTCIP();
				}
			}
			catch (ObjectDisposedException err) 
			{
				MessageBox.Show(err.Message);
			}
		
		}

		private void button3_Click(object sender, System.EventArgs e)
		{
			SendMulText();
		}

		private void SendMsg(string str)
		{
			mySoc.SendData(str);
		}

		private void button4_Click(object sender, System.EventArgs e)
		{
			mySoc.ReceiveData();
		}

		private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyValue==13)
			{
		        SendMulText();
			}
 
		}

		private void SendMulText()
		{
			string[] tempArray = new string [textBox1.Lines.Length];
			tempArray = textBox1.Lines;
 
			for(int counter=0; counter < tempArray.Length;counter++)
			{
				if (tempArray[counter].Length > 0)
				{
					//mySoc.SendData(tempArray[counter]);
					SendToAllConnectedUse(tempArray[counter]);
					
				}
				listBox1.Items.Add("Me >>"+ tempArray[counter]);
			}
			textBox1.Clear();
		}

		private void SendToAllConnectedUse(string data)
		{
          int nSoc;
			foreach (ListViewItem user in listView1.Items)
			{
				try
				{
					nSoc= Convert.ToInt32(user.SubItems[0].Text);
					if (SocClient[nSoc]!=null)
					{
						if (SocClient[nSoc].Soc.Connected)
							SocClient[nSoc].SendData(data);   
					}
				}
				catch (Exception err) 
				{
					label1.Text="GetSock :"+err.Message;
				}
			 
			}
		}

		private int GetAvailbleSocket()
		{
			int i=-1;
			for( i=0;i<MAX_SOCKET;i++)
			{
				try
           	    {
					if (SocClient[i]==null)
						break;
					else
 					{
					    if (!SocClient[i].Soc.Connected)
						    break;
					}
				}
			   catch (Exception err) 
			   {
			  	  label1.Text="GetSock :"+err.Message;
			   }

			}

          if ((i>-1)&& (i <MAX_SOCKET))  
			  InitSocket(ref SocClient[i],i);
          txtSoc.Text= "Select Socket is :"+i.ToString();
		  return i;
		}

		private void button4_Click_1(object sender, System.EventArgs e)
		{
			serverThread = new Thread(new ThreadStart(startListen));
			serverThread.Start();
			button4.Enabled=false;

		}

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

		private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (serverThread!=null)
			{
				if (serverThread.IsAlive)
				{
					if (ListenSoc.Soc.Connected)
					{
						ListenSoc.Soc.Shutdown(SocketShutdown.Both);
						ListenSoc.Soc.Close();
					}
					serverThread.Abort();
				}
			}
		}

		private void listView1_DoubleClick(object sender, System.EventArgs e)
		{	
			int pos = listView1.SelectedItems[0].Index; 
		    int nSoc = Convert.ToInt32(listView1.SelectedItems[0].SubItems[0].Text); 
			if (MessageBox.Show("Confirm to disconnect this user ?","Diconnect",MessageBoxButtons.YesNo)==DialogResult.Yes)
			{
				try
				{
					if (SocClient[nSoc]!=null)   	
					{
						if (SocClient[nSoc].Soc.Connected)
						{
							SocClient[nSoc].CloseSocket();
						}
					}
				}
				catch (Exception err) 
				{
					label1.Text="GetSock :"+err.Message;
				}
				
				
			}
		}

		private void butFileName_Click(object sender, System.EventArgs e)
		{
			if (openFile.ShowDialog(this)==DialogResult.OK)
			   txtFileName.Text = openFile.FileName;

		}

		private void bSendFile_Click(object sender, System.EventArgs e)
		{
			int nSoc;
			foreach (ListViewItem user in listView1.Items)
			{
				try
				{
					nSoc= Convert.ToInt32(user.SubItems[0].Text);
					if (SocClient[nSoc]!=null)
					{
						if (SocClient[nSoc].Soc.Connected)
							SocClient[nSoc].SendFile(txtFileName.Text);
					}
				}
				catch (Exception err) 
				{
					label1.Text="GetSock :"+err.Message;
				}
			 
			}
		}

	}
}

⌨️ 快捷键说明

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