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

📄 socket.cs

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

		//................................................
		//      Sending File function 
		//................................................
		public void SendFile(string filename)
		{
			try
			{
				SentFile = new FileStream(filename, FileMode.Open, FileAccess.Read); 
				int nPos = filename.LastIndexOf("\\");
				if (nPos > -1)
					filename = filename.Substring(nPos+1);
				string fileinfo;
				fileinfo="\x01\x53"+SentFile.Length.ToString()+"\x03"+filename+"\x04";
				bSendFile = true;
				SendData(fileinfo);
				SetSendFileTimer();
			}
			catch(Exception err)
			{
				CloseSendFile();
				RaiseSockErrEvent("File : "+filename+" Error:"+err.Message);
				return;
			}
		}

		private void SetSendFileTimer()
		{
		    SendfileTimer = new System.Timers.Timer();
			SendfileTimer.Elapsed+=new ElapsedEventHandler(OnSendFileTimedEvent);
			SendfileTimer.Interval=30000; //30 seconds
			SendfileTimer.Enabled=true;
		}

		private void OnStartSendFileTimer()
		{
		   SendfileTimer.Start();
           //RaiseMessageEvent("Timer Start");
		}

		private void OnStopSendFileTimer()
		{
			SendfileTimer.Stop();
			//RaiseMessageEvent("Timer Stop");
		}

		private void OnCloseSendFileTimer()
		{
			SendfileTimer.Close();
			//RaiseMessageEvent("Timer Closed");
		}

		private void OnSendFileTimedEvent(object source, ElapsedEventArgs e)
		{
            //no response after 30 seconds...
    		//so we just close the file and communication
            OnStopSendFileTimer();
			SendfileTimer.Close();
			RaiseSockErrEvent("Sending : Time-out for sending, Task cancel and connection closed");
			CloseSocket();
		}


		private void CloseSendFile()
		{
			try
			{  
				if (SendfileTimer!=null)
					OnCloseSendFileTimer();

				bSendFile = false;
				if (SentFile !=null)
				{
					SentFile.Close();
				    RaiseMessageEvent("File is Closed");
				}
			}
			catch(Exception err)
			{
			   RaiseMessageEvent(err.Message);
			}
		}

		private void SendbyteData(byte[] data,int dataLen)
		{
			try
			{
				Soc.BeginSend(data,0,dataLen,SocketFlags.None, 
					new AsyncCallback(SendFileCallback),Soc);
			}
			catch(Exception e)
			{
		
				RaiseSockErrEvent("Send : "+e.Message);
				CloseSocket();
			}

		}
		
		private void SendFileCallback(IAsyncResult ar)
		{
			try
			{
				Socket soc = (Socket)ar.AsyncState;
				int byteSend = soc.EndSend(ar);
				nTtlByteSend += byteSend;
				RaiseSendingFileEvent(SentFile.Length.ToString(),nTtlByteSend);
				
				//Finish Sending a block, stop Timer
				OnStopSendFileTimer();
				if( SentFile.Length!=SentFile.Position)
					StartSendFile();
				else
				{
				   CloseSendFile();
				}
				
			}
			catch(Exception e)
			{
				RaiseSockErrEvent("Send : "+e.Message);
			}
		}

		private void StartSendFile()
		{
			byte[] buff= new byte[513];
			try
			{
				if( SentFile.Length!=SentFile.Position)
				{
					OnStartSendFileTimer();
					int nRead= SentFile.Read(buff,0,512);
					if (nRead > 0)
						SendbyteData(buff,nRead);
				}
			}
			catch(Exception err)
			{
				RaiseSockErrEvent("Send File: Error:"+err.Message);
			}
	  	}

		//................................................
		//         Check Command 
		//................................................
		private void CheckCommand()
		{
			int nPos1;
			string strCmd = response.ToString();
            
			//Sending file status
			if ((nPos1=strCmd.IndexOf("\x02\x06"))>-1)
			{
				SentFileStatus(strCmd,nPos1) ;
				return;
			}

			//File is comming..file info
			if ((nPos1=strCmd.IndexOf("\x01\x53"))>-1)
			{
				IncommingFileInfo(strCmd,nPos1) ;
				return;
			}

            //normal chating message
            response.Remove(0,strCmd.Length);
			RaiseMessageEvent(strCmd);
           
		}

		private void SentFileStatus(string strCmd,int nPos)
		{
			int nPos2=strCmd.IndexOf("\x03");
			int nCommand; 
			
			if (nPos2>-1)
				nCommand = Convert.ToInt32(strCmd.Substring(nPos+2,nPos2-nPos-2));
			else return; //back, cause the command string not fully received yet
            
			//Need to stop the timer, cause the sending response is back
			OnStopSendFileTimer();

			switch(nCommand)
			{
				case 2101:
					RaiseMessageEvent("File is send.. ");
					break;
				case 3100:
					nTtlByteSend =0;
					StartSendFile();
					break;
				case 3103:
				case 3104: 
					if (SentFile!=null)
					{
						RaiseMessageEvent("Fail to send file "+SentFile.Name);
						SentFile.Close();//Remote PC reject this file, so close it.
					}
					break;
			} 
 	
			if (nPos2 > 1)
				response.Remove(nPos,nPos2-nPos+1);
		}
		
		//Receiveing File
		private void IncommingFileInfo(string strCmd,int nPos1) 
		{
          int nPos2=strCmd.IndexOf("\x03");
		  int nPos3=strCmd.IndexOf("\x04");
          string cmd;
            
		    if ((nPos2==-1) || (nPos3==-1)) return;
			response.Remove(nPos1,nPos3-nPos1+1);
	        
			RecvFilename = Directory.GetCurrentDirectory()+@"\"+strCmd.Substring(nPos2+1,nPos3-nPos2-1); 		  
			nRecFileSize =Convert.ToInt32(strCmd.Substring(nPos1+2,nPos2-nPos1-2));
			RaiseMessageEvent(RecvFilename); 
            
			if (nRecFileSize==0)
			{
				cmd="\x02\x06\x33\x31\x30\x33\x03";
				SendData(cmd);
				return ;
			}
			try
			{
				RecvFile = new FileStream(RecvFilename, FileMode.Create, FileAccess.Write,FileShare.None); 
			}
			catch(Exception err)
			{
				cmd="\x02\x06\x33\x31\x30\x33\x03";
				SendData(cmd);
				RaiseMessageEvent("RecvFile  : "+RecvFilename+" Error:"+err.Message);
				return;
			}
			cmd="\x02\x06\x33\x31\x30\x30\x03";
			SendData(cmd); 
			//Set the timer, if no response in 60 second, stop the receiving process
			SetRecvFileTimer();

			bClosedRecvFile = false;
			bRecvFile       = true;
			nWritebyte      = 0;
		}

		private void StoreToRecvFile(byte[] data,int nLen)
		{
			nWritebyte +=nLen;
			try
			{
				OnStopRecvFileTimer();
				RecvFile.BeginWrite(data,0,nLen,new AsyncCallback(FileWriteCallback),RecvFile);
			}
			catch(Exception err)
			{
				RaiseMessageEvent("Recv BFile: Error:"+err.Message);
			}
		}

		private void FileWriteCallback(IAsyncResult ar)
		{
			try
			{   
				FileStream file =(FileStream)ar.AsyncState;
				file.EndWrite(ar);
				OnStartRecvFileTimer();
				RaiseReceivingEvent(nRecFileSize.ToString(),nWritebyte);
				if (nWritebyte >=nRecFileSize)
				{  
					bRecvFile  = false;
				   	CloseRecvFile();
				}
			}
			catch(Exception err)
			{
				RaiseMessageEvent("Recv File2: Error:"+err.Message);
			}
		}
		private void CloseRecvFile()
		{
			if (bClosedRecvFile) return;
			try
			{  
				OnCloseRecvFileTimer();
				bRecvFile  = false;
				nWritebyte = 0;
				nRecFileSize=0;
		        RecvFilename="";
			    bClosedRecvFile = true;	
				if (RecvFile !=null)
				{
					RecvFile.Close();
			        RaiseMessageEvent("Recv File is Closed.");
			
				}

			    SendData("\x02\x06\x32\x31\x30\x31\x03");
               
			}
			catch(Exception err)
			{
				RaiseMessageEvent(err.Message);
			}
		}

		private void SetRecvFileTimer()
		{
			RecvfileTimer = new System.Timers.Timer();
			RecvfileTimer.Elapsed+=new ElapsedEventHandler(OnRecvFileTimedEvent);
			RecvfileTimer.Interval=60000; //60 seconds
			RecvfileTimer.Enabled=true;
		}
		private void OnStartRecvFileTimer()
		{
			RecvfileTimer.Start();
			RaiseMessageEvent("Timer Start");
		}

		private void OnStopRecvFileTimer()
		{
			RecvfileTimer.Stop();
			RaiseMessageEvent("Timer Stop");
		}

		private void OnCloseRecvFileTimer()
		{
			RecvfileTimer.Close();
			RaiseMessageEvent("Timer Closed");
		}

		private void OnRecvFileTimedEvent(object source, ElapsedEventArgs e)
		{
			OnStopRecvFileTimer();
			RecvfileTimer.Close();
			RaiseSockErrEvent("Receiving: Time-out for file receiving, Task cancel and connection closed");
			CloseRecvFile();
		}

	} //end WSocket Class
   
	

	
}

⌨️ 快捷键说明

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