using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace Server_Download
{
    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();
            


            Encoding getIniFileEncoding = GetIniFileEncoding(Environment.CurrentDirectory + "\\Config.ini");
            if (getIniFileEncoding != Encoding.Unicode)
            {
                string text = File.ReadAllText(Environment.CurrentDirectory + "\\Config.ini", getIniFileEncoding);
                File.WriteAllText(Environment.CurrentDirectory + "\\Config.ini", text, Encoding.Unicode);
            }



            StringBuilder Side_ = new StringBuilder(1024);
            GetPrivateProfileString("Config", "Side", "1", Side_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Side = Side_.ToString();

            StringBuilder Update_time_ = new StringBuilder(1024);
            GetPrivateProfileString("Config", "Update_time", "1", Update_time_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Update_time = Update_time_.ToString();

            StringBuilder SET_PORT_ = new StringBuilder(1024);
            GetPrivateProfileString("Server", "SET_PORT", "9988", SET_PORT_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            SET_PORT = SET_PORT_.ToString();

            StringBuilder Client_IP_ = new StringBuilder(1024);
            GetPrivateProfileString("Client", "Server_IP", "127.0.0.1", Client_IP_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Server_IP = Client_IP_.ToString();

            StringBuilder Client_PORT_ = new StringBuilder(1024);
            GetPrivateProfileString("Client", "Server_PORT", "9988", Client_PORT_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Server_PORT = Client_PORT_.ToString();



            StringBuilder Copy_Enabled_ = new StringBuilder(255);
            GetPrivateProfileString("Client", "Copy_Enabled", "0", Copy_Enabled_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Copy_Enabled = Copy_Enabled_.ToString();
            StringBuilder Copy_Path_ = new StringBuilder(255);
            GetPrivateProfileString("Client", "Copy_Path", "", Copy_Path_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Copy_Path = Copy_Path_.ToString();
            StringBuilder Paste_Path_ = new StringBuilder(255);
            GetPrivateProfileString("Client", "Paste_Path", "", Paste_Path_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            Paste_Path = Paste_Path_.ToString();


            StringBuilder File_Name_ = new StringBuilder(255);
            GetPrivateProfileString("Client", "File_Name", "", File_Name_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            File_Name = File_Name_.ToString();

            StringBuilder Save_Path_ = new StringBuilder(255);
            GetPrivateProfileString("Client", "Save_Path", Environment.CurrentDirectory, Save_Path_, 1024, Environment.CurrentDirectory + "\\Config.ini");
            if (Save_Path_.ToString() == "")
            {
                Save_Path = Environment.CurrentDirectory;
            }
            else {

                Save_Path = Save_Path_.ToString();
            }


            for (int i=1;i<100 ;i++) {
                StringBuilder name = new StringBuilder(255);
                GetPrivateProfileString("Process", "name"+i, "", name, 1024, Environment.CurrentDirectory + "\\Config.ini");
                if (name.ToString() != "")
                {
                    jc_name.Add(name.ToString());
                }
                else {
                    break;
                }
            }
            


           
        }

        protected override void DefWndProc(ref System.Windows.Forms.Message m)
        {
            //string message;
            //richTextBox1.AppendText(ax++ + "\r\n");
            switch (m.Msg)
            {//

                case WM_SINFO://处理消息

                    richTextBox1.SelectionStart = richTextBox1.TextLength;

                    // Scrolls the contents of the control to the current caret position.
                    richTextBox1.ScrollToCaret(); //Caret意思：脱字符号；插入符号; (^)
                    break;

                case WM_SINFO1://处理消息

                    richTextBox1.AppendText(System.DateTime.Now.ToString(("yyyy-MM-dd hh:mm:ss:fff") + ":  "));
                    richTextBox1.SelectionColor = Color.Black;
                    richTextBox1.AppendText(Marshal.PtrToStringAnsi(m.LParam) + "\r\n");
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.ScrollToCaret();
                    break;
                case WM_SINFO2:
                    //message = string.Format("收到从应用程序发出的消息！参数为：{0}, {1}", m.WParam, m.LParam);
                    richTextBox1.AppendText(System.DateTime.Now.ToString(("yyyy-MM-dd hh:mm:ss:fff") + ":  "));
                    richTextBox1.SelectionColor = Color.Green;
                    richTextBox1.AppendText(Marshal.PtrToStringAnsi(m.LParam) + "\r\n");
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.ScrollToCaret();
                    break;
                case WM_SINFO3://处理消息

                    richTextBox1.AppendText(System.DateTime.Now.ToString(("yyyy-MM-dd hh:mm:ss:fff") + ":  "));
                    richTextBox1.SelectionColor = Color.Red;
                    richTextBox1.AppendText(Marshal.PtrToStringAnsi(m.LParam) + "\r\n");
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.ScrollToCaret();
                    break;

                default:
                    base.DefWndProc(ref m);
                    break;
            }

        }


        public static Encoding GetIniFileEncoding(string filePath)
        {
            Encoding encoding = Encoding.Default;
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                // 获取文件流中的字节序列
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);

                // 检测字节序列的编码格式
                if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
                {
                    encoding = Encoding.UTF8;
                }
                else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
                {
                    encoding = Encoding.BigEndianUnicode;
                }
                else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
                {
                    encoding = Encoding.Unicode;
                }
                else
                {
                    // 如果没有检测到BOM，则使用默认编码格式
                    encoding = Encoding.Default;
                }
            }
            return encoding;
        }
       
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int Informtion_SendMessage(IntPtr hWnd, int msg, uint wParam, IntPtr lParam);
       
        public const int USER = 0x0400;
        public const int WM_SINFO1 = USER + 101;
        public const int WM_SINFO2 = USER + 102;
        public const int WM_SINFO3 = USER + 103;
        public const int WM_SINFO = USER + 104;
        public const int WM_LOG = USER + 105;
        public const int WM_DGV1 = USER + 106;
        IntPtr handle = IntPtr.Zero;
        public void new_Show_Informtion(string Text, int Result_information)
        {
            if (Result_information == 3)
            {
                // timer1.Stop();
                Informtion_SendMessage(handle, WM_SINFO3, 0, Marshal.StringToHGlobalAnsi(Text));

            }
            else if (Result_information == 2)
            {
                // timer1.Stop();
                Informtion_SendMessage(handle, WM_SINFO2, 0, Marshal.StringToHGlobalAnsi(Text));
            }
            else if (Result_information == 1)
            {
                Informtion_SendMessage(handle, WM_SINFO1, 0, Marshal.StringToHGlobalAnsi(Text));
            }


        }
        

        #region 服务端
        static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };
        // 创建一个和客户端通信的套接字
        static Socket socket_Server = null;
        /// <summary>
        /// 服务器监听
        /// </summary>
        public void Server_Monitor(int Port)
        {
            //定义一个套接字用于监听客户端发来的消息，包含三个参数（IP4寻址协议，流式连接，Tcp协议）  
            socket_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //将IP地址和端口号绑定到网络节点point上 
            IPEndPoint point = new IPEndPoint(IPAddress.Any, Port);
            //MessageBox.Show(IPAddress.Any.ToString());
            //监听绑定的网络节点  
            socket_Server.Bind(point);

            //将套接字的监听队列长度限制为50  
            socket_Server.Listen(50);

            //负责监听客户端的线程:创建一个监听线程  
            Thread threadwatch = new Thread(watchconnecting);

            //将窗体线程设置为与后台同步，随着主线程结束而结束  
            threadwatch.IsBackground = true;

            //启动线程     
            threadwatch.Start();

            new_Show_Informtion("Start listening...", 1);

            


        }
        /// <summary>
        /// 服务器监听事件
        /// </summary>
        void watchconnecting()
        {
            try {
                Socket connection = null;

                //持续不断监听客户端发来的请求     
                while (true)
                {
                    try
                    {
                        connection = socket_Server.Accept();
                    }
                    catch (Exception ex)
                    {
                        new_Show_Informtion(ex.Message, 3);
                        break;
                    }

                    //获取客户端的IP和端口号  
                    IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                    int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

                    //让客户显示"连接成功的"的信息  
                    string sendmsg = "Successfully connected to the server!\r\n" + "Local IP:" + clientIP + ",Local Port:" + clientPort.ToString()+ "?"+ Update_time;
                    
                    byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                    //实际发送的字节数组比实际输入的长度多1，用于存取标识符
                    //标识符添加在位置为0的地方
                    byte[] newBuffer = new byte[arrSendMsg.Length + 1];
                    newBuffer[0] = 0;
                    Buffer.BlockCopy(arrSendMsg, 0, newBuffer, 1, arrSendMsg.Length);
                    connection.Send(newBuffer);
                    //客户端网络结点号  
                    string remoteEndPoint = connection.RemoteEndPoint.ToString();

                    //显示与客户端连接情况
                    new_Show_Informtion("Successfully established connection with client " + remoteEndPoint + "!\t\n", 1);

                    //添加客户端信息  
                    clientConnectionItems.Add(remoteEndPoint, connection);


                    IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;

                    //创建一个通信线程      
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRec);
                    Thread thread = new Thread(pts);
                    //设置为后台线程，随着主线程退出而退出 
                    thread.IsBackground = true;
                    //启动线程     
                    thread.Start(connection);
                }
            } catch (Exception EX) {
                new_Show_Informtion("Error:" + EX.Message , 3);
            }

        }
        /// <summary>
        /// 单条连接
        /// </summary>
        /// <param name="obj"></param>
        private void ServerRec(object obj)
        {
            try {
                string recStr = null;
                Socket socketServer = obj as Socket;
                long fileLength = 0;
                while (true)
                {
                    int firstRcv = 0;
                    byte[] buffer = new byte[8 * 1024];
                    try
                    {
                        if (socketServer != null) firstRcv = socketServer.Receive(buffer);
                        if (firstRcv > 0)//大于0，说明有东西传过来
                        {
                            if (buffer[0] == 0)//0对应文字信息
                            {
                                recStr = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1);
                                //对接收的路径进行打包发送
                                //new_Show_Informtion("客户端_" + socketServer.RemoteEndPoint + ":" + recStr, 1);
                                new_Show_Informtion("Client_" + socketServer.RemoteEndPoint + ":" + recStr, 2);
                                
                                string[] value = new string[2] { socketServer.RemoteEndPoint.ToString(), recStr.ToString() };
                                ParameterizedThreadStart pts = new ParameterizedThreadStart(SendFile_);
                                Thread thread_server_r = new Thread(pts);
                                //设置为后台线程，随着主线程退出而退出 
                                thread_server_r.IsBackground = true;
                                //启动线程     
                                thread_server_r.Start(value);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());
                        new_Show_Informtion("Client Count:" + clientConnectionItems.Count, 3);
                        new_Show_Informtion("System abnormality:" + ex.Message, 3);
                        break;
                    }

                }
            } catch (Exception ex)
            {
                new_Show_Informtion("Error:" + ex.Message, 3);
            }
            

        }
        
        public void SendFile_(object obj) {

            string[] value = (string[])obj;
            try {
                new_Show_Informtion("Send file for "+ value[0], 1);
                string SendFile_path = Environment.CurrentDirectory + "\\" + value[1].ToString();
                if (CompressZipFile_ok.Contains(Path.GetFileNameWithoutExtension(SendFile_path)))
                {
                    new_Show_Informtion("Waiting for compression!" + value[0], 1);
                    for (; ; )
                    {
                        Application.DoEvents();
                        if (!CompressZipFile_ok.Contains(Path.GetFileNameWithoutExtension(SendFile_path)))
                        {
                            break;
                        }
                        Delay(500);
                    }
                    new_Show_Informtion("Compression completed!" + value[0], 1);
                }
                if (!File.Exists(SendFile_path)) 
                {

                    if (!Directory.Exists(Path.GetDirectoryName(SendFile_path) + "\\" + Path.GetFileNameWithoutExtension(SendFile_path)))
                    {
                        SendStr("Error:The server did not find the file.", 3, value[0]);
                    }
                    else {
                        new_Show_Informtion("Compressed file [" + Path.GetDirectoryName(SendFile_path) + "\\" + Path.GetFileNameWithoutExtension(SendFile_path) +"] "+ value[0], 1);
                        CompressZipFile_ok.Add(Path.GetFileNameWithoutExtension(SendFile_path));
                        if (!compressedFile(Path.GetDirectoryName(SendFile_path) + "\\" + Path.GetFileNameWithoutExtension(SendFile_path), SendFile_path))
                        {
                            SendStr("Error:Server compression failed.", 3, value[0]);
                        }
                        //Compress(Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path), path);
                    }
                    
                }

                new_Show_Informtion("file name:" + value[1], 1);
                new_Show_Informtion("ip:" + value[0], 1);
                SendFile(SendFile_path, value[1], value[0]);
            }
            catch (Exception ex) {
                SendStr("Error:" + ex.Message,3,value[0]);
                new_Show_Informtion("Error:" + ex.Message, 3); 
            }
            
        }

        #endregion


        #region 发送
        
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="SendStr">内容</param>
        /// <param name="symbol"></param>
        /// <param name="IP">地址</param>
        private void SendStr(string SendStr, byte symbol, string IP)
        {
            try
            {
                Socket socketclientparalhy;
                //用UTF8能接受文字信息
                byte[] buffer = Encoding.UTF8.GetBytes(SendStr);
                //实际发送的字节数组比实际输入的长度多1，用于存取标识符
                byte[] newBuffer = new byte[buffer.Length + 1];
                //标识符添加在位置为0的地方
                newBuffer[0] = symbol;
                Buffer.BlockCopy(buffer, 0, newBuffer, 1, buffer.Length);
                clientConnectionItems.TryGetValue(IP, out socketclientparalhy);
                //;
                new_Show_Informtion(Encoding.UTF8.GetString(newBuffer, 1, newBuffer.Length - 1), 2);
                socketclientparalhy.Send(newBuffer);
                new_Show_Informtion(SendStr, 1);
            }
            catch (Exception exx)
            {
                new_Show_Informtion("An error occurred：" + exx.Message, 3);
            }
        }
       
        private void SendFile(string fileFullPath, string fileName, string IP)
        {
            
            Socket socketclientparalhy;
           
            if (!File.Exists(fileFullPath))
            {
                new_Show_Informtion("file does not exist!"+ IP, 3);
                SendStr("file does not exist!", 3, IP);
                return;
            }
            
            //发送文件前，将文件名和长度发过去

            long fileLength = new FileInfo(fileFullPath).Length;
            
            string totalMsg = string.Format("{0}-{1}", fileName, fileLength);
            
            SendStr(totalMsg, 2, IP);

            Delay(2000);

            byte[] buffer = new byte[8 * 1024];


            using (FileStream fs = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read))
            {
                int readLength = 0;
                bool firstRead = true;
                long sentFileLength = 0;
                while ((readLength = fs.Read(buffer, 0, buffer.Length)) > 0 && sentFileLength < fileLength)
                {
                    sentFileLength += readLength;
                    //第一次发送的字节流上加个前缀1
                    if (firstRead)
                    {
                        byte[] firstBuffer = new byte[readLength + 1];
                        //标记1，代表为文件
                        firstBuffer[0] = 1;
                        Buffer.BlockCopy(buffer, 0, firstBuffer, 1, readLength);
                        clientConnectionItems.TryGetValue(IP, out socketclientparalhy);
                        socketclientparalhy.Send(firstBuffer, 0, readLength + 1, SocketFlags.None);
                        firstRead = false;
                        continue;
                    }
                    clientConnectionItems.TryGetValue(IP, out socketclientparalhy);
                    socketclientparalhy.Send(buffer, 0, readLength, SocketFlags.None);
                }
                fs.Close();

            }

            new_Show_Informtion("Sent file:" + fileName+ " to "+IP+" OK. ", 1);

        }

        #endregion

        bool khd_xc = true;

        #region 客户端
        Thread thread_client = null;
        Socket socket_client = null;
        public void Client(string IP,int Port) {
            //定义一个套接字监听  
            socket_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //获取文本框中的IP地址  
            IPAddress address = IPAddress.Parse(IP.ToString());//127.0.0.1

            //将获取的IP地址和端口号绑定在网络节点上  
            IPEndPoint point = new IPEndPoint(address, Port);

            try
            {
                //客户端套接字连接到网络节点上，用的是Connect  
                socket_client.Connect(point);
                new_Show_Informtion("Connected to server " + point + "\r\n", 1);

            }
            catch (Exception esx)
            {
                Debug.WriteLine("connection failed.\r\n");
                new_Show_Informtion("connection failed:" + esx.Message + "\r\n", 3);
                err++;
                return;
            }
            khd_xc = false;
            thread_client = new Thread(RecMsg);
            thread_client.IsBackground = true;
            thread_client.Start();
            for (; ; ) {
                Application.DoEvents();
                if (khd_xc) {
                    break;
                }
                Delay(100);
            }
        }
        int err = 0;
        /// <summary>
        /// 客户端监听事件
        /// </summary>
        [DllImport("kernel32.dll")]
        static extern bool WritePrivateProfileString(string section, string key, string value, string filePath);
        string[] rt = new string[2];
        private void RecMsg()
        {
            long fileLength = 0;
            string recStr = null;
            
            while (true)
            {
                try
                {
                    int firstRcv = 0;
                    byte[] buffer = new byte[8 * 1024];
                    if (socket_client != null) firstRcv = socket_client.Receive(buffer);
                    if (firstRcv > 0)
                    {
                        if (buffer[0] == 0)
                        {
                            recStr = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1);
                            new_Show_Informtion("Server:" + recStr + "\r\n", 2);
                            rt = recStr.Split('?');
                            if (rt.Length >= 2 && rt[1] == Update_time)
                            {
                                new_Show_Informtion("No update required", 1);
                                string zippath = Save_Path + "\\" + File_Name;
                                //Delay(800);
                                if (Directory.Exists(Path.GetDirectoryName(zippath) + "\\" + Path.GetFileNameWithoutExtension(zippath))) {
                                    System.Diagnostics.Process.Start("explorer.exe", Path.GetDirectoryName(zippath) + "\\" + Path.GetFileNameWithoutExtension(zippath));
                                    //System.Diagnostics.Process.Start(Path.GetDirectoryName(zippath) + "\\" + Path.GetFileNameWithoutExtension(zippath));
                                }
                                else
                                {
                                    new_Show_Informtion("Open failed!", 3);
                                }
                                Delay(800);
                                khd_xc = true;
                                return;
                            }
                            
                            string yjj_path = Path.GetDirectoryName(Save_Path + "\\" + File_Name) + "\\" + Path.GetFileNameWithoutExtension(Save_Path + "\\" + File_Name);
                            new_Show_Informtion("Start deleting files[" + yjj_path + "]", 1);
                            bool del = false;
                            if (Directory.Exists(Path.GetDirectoryName(Save_Path + "\\" + File_Name) + "\\" + Path.GetFileNameWithoutExtension(Save_Path + "\\" + File_Name)))
                            {
                                //MessageBox.Show(Path.GetDirectoryName(Save_Path + "\\" + File_Name) + "\\" + Path.GetFileNameWithoutExtension(Save_Path + "\\" + File_Name));
                                del = deleteF(Path.GetDirectoryName(Save_Path + "\\" + File_Name) + "\\" + Path.GetFileNameWithoutExtension(Save_Path + "\\" + File_Name));
                                
                            }
                            else {
                                del = true;
                            }
                            if (File.Exists(Save_Path + "\\" + recStr))
                            {
                                File.Delete(Save_Path + "\\" + recStr);

                            }

                            if (del && !Directory.Exists(yjj_path))
                            {
                               
                                ClientSend(File_Name, 0);//?
                                new_Show_Informtion("Start waiting for the server to send files.", 1);
                            }
                            else {
                                new_Show_Informtion("File deletion failed:Please confirm if there are any background processes occupying it!", 3);
                                err++;
                            }
                            
                            
                        }
                        if (buffer[0] == 3)
                        {
                            recStr = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1);
                            new_Show_Informtion("Server:" + recStr + "\r\n", 3);
                            err++;
                        }
                        if (buffer[0] == 1)
                        {
                            
                            this.Invoke((EventHandler)(delegate
                            {
                                progressBar1.Minimum = 0;
                                progressBar1.Maximum = 100;
                            }));
                           
                            if (!Directory.Exists(Save_Path))
                            {
                                Directory.CreateDirectory(Save_Path);
                            }
                            string savePath = Save_Path + "\\" + recStr;
                            int rec = 0;
                            long recFileLength = 0;
                            bool firstWrite = true;
                            new_Show_Informtion("Start receiving files!", 1);
                            using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                            {


                                while (recFileLength < fileLength)
                                {
                                    this.Invoke((EventHandler)(delegate
                                    {
                                        progressBar1.Value = (int)((((float)recFileLength / (float)fileLength) * 100) + 1);
                                        label2.Text = progressBar1.Value + "%";
                                    }));

                                    Application.DoEvents();
                                    if (firstWrite)
                                    {
                                        fs.Write(buffer, 1, firstRcv - 1);
                                        fs.Flush();
                                        recFileLength += firstRcv - 1;
                                        firstWrite = false;
                                    }
                                    else
                                    {
                                        rec = socket_client.Receive(buffer);
                                        fs.Write(buffer, 0, rec);
                                        fs.Flush();
                                        recFileLength += rec;
                                    }
                                    
                                    
                                    Application.DoEvents();
                                }
                                fs.Close();
                                this.Invoke((EventHandler)(delegate
                                {
                                    progressBar1.Value = (int)((((float)recFileLength / (float)fileLength) * 100) );
                                    label2.Text = progressBar1.Value + "%";
                                }));

                            }
                            new_Show_Informtion("Receiving completed!", 1);
                            string fName = savePath.Substring(savePath.LastIndexOf("\\") + 1);
                            string fPath = savePath.Substring(0, savePath.LastIndexOf("\\"));
                            new_Show_Informtion("You have successfully received files from the server:" + "\r\n" + fName + " Save path as:" + fPath + "\r\n", 2);
                            if (File.Exists(savePath))
                            {
                                
                                new_Show_Informtion("Start decompressing!", 1);

                                Extract_pok_OK = false;
                                //Thread t_e = new Thread(new ParameterizedThreadStart(Extract_pok_));
                                // 启动线程，并传入参数
                                //t_e.Start(savePath);
                                //t_e.IsBackground = true;
                                Extract_pok_(savePath);
                                for (; ; )
                                {
                                    Application.DoEvents();
                                    if (Extract_pok_OK)
                                    {
                                        break;
                                    }
                                    Delay(100);
                                }
                                //Extract(savePath, Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath));
                                //Decompression(Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath), savePath);
                            }
                            //Delay(800);
                            new_Show_Informtion("[" + Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath) + "]OK", 1);
                            if (Directory.Exists(Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath)))
                            {
                                System.Diagnostics.Process.Start("explorer.exe", Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath));
                                //System.Diagnostics.Process.Start(Path.GetDirectoryName(savePath) + "\\" + Path.GetFileNameWithoutExtension(savePath));
                            }
                            else {
                                new_Show_Informtion("Open failed!", 3);
                            }
                            Delay(800);
                            break;

                        }
                        if (buffer[0] == 2)
                        {
                            string fileNameWithLength = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1);
                            new_Show_Informtion(fileNameWithLength, 1);
                            recStr = fileNameWithLength.Split('-').First();
                            fileLength = Convert.ToInt64(fileNameWithLength.Split('-').Last());

                            new_Show_Informtion("Server:[" + recStr + "]["+ fileLength+"]", 2); 
                        }
                    }
                }
                catch (Exception ex)
                {
                    new_Show_Informtion("An error occurred:" + ex.Message, 3);
                    err++;
                    break;
                }
            }
            khd_xc = true;
        }
        Process process_JY;
        public void Extract_pok_(object STR)
        {
            
            try {
                string pathTo7z = Environment.CurrentDirectory + @"\7-zip\7z.exe";// @"D:\MyRepository\WorkRepository\Production_Do not modify\TOOL\Server_Download\Server_Download\bin\x86\Debug\7-Zip\7z.exe"; // 7z.exe 文件路径
                string archivePath = Path.GetFullPath(STR.ToString());// @"D:\MyRepository\FTA.rar"; // 要解压缩的文件路径Path.GetFullPath(value.ToString()), Path.GetDirectoryName(value.ToString()) + "\\" + Path.GetFileNameWithoutExtension(value.ToString())
                string destinationPath = Path.GetDirectoryName(STR.ToString()) + "\\" + Path.GetFileNameWithoutExtension(STR.ToString());// @"D:\MyRepository\FTA"; // 解压缩的目标路径
                                                                                                                                         //string[] val;
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = pathTo7z;
                processStartInfo.Arguments = string.Format("x \"{0}\" -o\"{1}\" -bsp1 -bso0 -bse1", archivePath, destinationPath); //"x -y \"" + archivePath + "\" -oextracted -bso1 -bsp0";
                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.CreateNoWindow = true;
                process_JY = new Process();
                process_JY.StartInfo = processStartInfo;

                // 订阅输出事件
                process_JY.OutputDataReceived += (sender, e) =>
                {
                    //
                    if (e.Data != null)
                    {
                        
                        if (e.Data.IndexOf("-") > -1 && e.Data.IndexOf("%") > -1)
                        {
                            this.Invoke((EventHandler)(delegate
                            {
                                //progressBar1.Value = int.Parse(e.Data.Split('%')[0].ToString());
                                label3.Text = e.Data;
                            })); Application.DoEvents();
                            if (progressBar2.Value != int.Parse(e.Data.Split('%')[0].ToString()))
                            {
                                //Console.WriteLine(">" + e.Data.Split('%')[0]);
                                this.Invoke((EventHandler)(delegate
                                {
                                    progressBar2.Value = int.Parse(e.Data.Split('%')[0].ToString());
                                    //label1.Text = (e.Data.Split('%')[0].ToString()) + "%";
                                }));
                                
                            }
                        }
                        /*else
                        {
                            Console.WriteLine(e.Data);
                        }*/

                    }

                };
                process_JY.EnableRaisingEvents = true;
                process_JY.Exited += new EventHandler(pz_Exited);
                process_JY.Start();
                process_JY.BeginOutputReadLine();

                process_JY.WaitForExit();
            } catch (Exception ex) {
                this.Invoke((EventHandler)(delegate
                {
                    new_Show_Informtion(ex.Message, 3);
                }));
                err++;
                Extract_pok_OK = true;
            }
            
        }
        Process process_YS;
        public bool compressedFile(string sourceFile, string destinationFile)
        {

            try
            {
                if (sourceFile.ToString() != "" && Directory.Exists(sourceFile.ToString()))
                {
                    string pathTo7z = Environment.CurrentDirectory + @"\7-zip\7z.exe";
                    ProcessStartInfo processStartInfo = new ProcessStartInfo();
                    processStartInfo.FileName = pathTo7z;
                    processStartInfo.Arguments = string.Format("a \"{0}\" \"{1}\" -bsp1 -bso0 -bse1", destinationFile, sourceFile);//-bsp1 -bso0 -bse1 //"x -y \"" + archivePath + "\" -oextracted -bso1 -bsp0";
                    processStartInfo.UseShellExecute = false;
                    processStartInfo.RedirectStandardOutput = true;
                    processStartInfo.CreateNoWindow = true;
                    process_YS = new Process();
                    process_YS.StartInfo = processStartInfo;

                    // 订阅输出事件
                    process_YS.OutputDataReceived += (sender, e) =>
                    {
                        //Console.WriteLine(e.Data);
                        this.Invoke((EventHandler)(delegate
                        {
                            new_Show_Informtion("[" + destinationFile +"]"+e.Data, 1);
                        }));

                    };
                    process_YS.EnableRaisingEvents = true;
                    process_YS.Exited += new EventHandler(YS_Exited);
                    process_YS.Start();
                    process_YS.BeginOutputReadLine();

                    process_YS.WaitForExit();
                    new_Show_Informtion("DeCompress file[" + destinationFile + "] OK!", 2);
                    CompressZipFile_ok.Remove(Path.GetFileNameWithoutExtension(destinationFile));
                    return true;

                }
                else
                {
                    new_Show_Informtion("DeCompress File[" + destinationFile + "] Error!", 3);
                    CompressZipFile_ok.Remove(Path.GetFileNameWithoutExtension(destinationFile));
                    return false;
                }
                
            }
            catch (Exception ex)
            {
                this.Invoke((EventHandler)(delegate
                {
                    new_Show_Informtion(ex.Message, 3);
                }));
                CompressZipFile_ok.Remove(Path.GetFileNameWithoutExtension(destinationFile));
                return false;
            }

        }

        private void YS_Exited(object sender, EventArgs e)
        {

            this.Invoke((EventHandler)(delegate
            {
                
                new_Show_Informtion("Compression End!", 1);
                
            }));
            
        }
        bool Extract_pok_OK = true;
       
        private void pz_Exited(object sender, EventArgs e)
        {

            this.Invoke((EventHandler)(delegate
            {
                new_Show_Informtion("Decompression completed!", 2);
                progressBar2.Value = 100;
                label3.Text = "100%";
            }));
            Extract_pok_OK = true;
        }
        private void ClientSend(string SendStr, byte symbol)

        {

            byte[] buffer = Encoding.UTF8.GetBytes(SendStr);

            byte[] newBuffer = new byte[buffer.Length + 1];

            newBuffer[0] = symbol;

            Buffer.BlockCopy(buffer, 0, newBuffer, 1, buffer.Length);

            socket_client.Send(newBuffer);
            new_Show_Informtion(SendStr, 1);

        }

        #endregion









        string Save_Path = "";
        string SET_PORT = "9988";
        string Server_IP = "127.0.0.1";
        string Server_PORT = "9988";
        string File_Name = "";
        string Side = "1";
        string Update_time = "20130101";

        string Copy_Enabled = "0";
        string Copy_Path = "";
        string Paste_Path = "";
        private void button1_Click(object sender, EventArgs e)
        {
            Server_Monitor(int.Parse(SET_PORT));
            button1.Enabled = false;
        }



        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        private void Form1_Load(object sender, EventArgs e)
        {
            handle = this.Handle;
            string executablePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string executableName = Path.GetFileNameWithoutExtension(executablePath); //Path.GetFileName();
            this.Text= executableName;

            if (Side.ToUpper() == "0")
            {
                GB_Client.Visible = false;
                GB_Server.Visible = true;
                new_Show_Informtion(SET_PORT, 1);

            }
            else if (Side.ToUpper() == "1")
            {
                this.ControlBox = false;
                GB_Client.Visible = true;
                GB_Server.Visible = false;
                new_Show_Informtion(Server_IP, 1);
                new_Show_Informtion(Server_PORT, 1);
                new_Show_Informtion(File_Name, 1);
                new_Show_Informtion(Save_Path, 1);
                new_Show_Informtion(jc_name.Count.ToString(), 1);


            }
            new_Show_Informtion("Config OK", 1);


        }
        
        
        private void btnConnection_Click(object sender, EventArgs e)
        {
            btnConnection.Enabled = false;
            
            progressBar1.Value = 0;
            label2.Text = "";
            progressBar2.Value = 0;
            label3.Text = "";
            Delay(100);
           
            new_Show_Informtion("Start updating!", 1);
            Application.DoEvents();
            err = 0;
            Client(Server_IP, int.Parse(Server_PORT));
            if (Copy_Enabled == "1") {
                try { 
                    File.Copy(Copy_Path, Paste_Path, true);
                    new_Show_Informtion("Successfully replaced file!", 1);
                } catch (Exception ex) {
                    new_Show_Informtion(ex.Message, 3);
                }
                
                
            }else
            { new_Show_Informtion("No need to replace!", 1); }
            Delay(1000);
            btnConnection.Enabled = true;
            if (err == 0)
            {
                
                WritePrivateProfileString("Config", "Update_time", rt[1], Environment.CurrentDirectory + "\\Config.ini");

                new_Show_Informtion("Close.", 1);
                StopProcess(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            }
            else {
                new_Show_Informtion(err.ToString(), 1);
                this.ControlBox = true;
            }
            


        }
        
        
        
        public static void StopProcess(string processName)
        {
            try
            {
                System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(processName);
                foreach (System.Diagnostics.Process p in ps)
                {
                    p.Kill();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
       
        List<string> CompressZipFile_ok = new List<string>();
       
        public bool deleteF(string val) {
            try {

                //delete_file(val);
                delete_file_();
                new_Show_Informtion("Process shutdown OK", 2);
                new_Show_Informtion("Deleting file, please wait...", 1);
                DeleteFolder(val);
                new_Show_Informtion("File deleted successfully.", 2); 
                return true;
            } catch (Exception ex)
            {
                new_Show_Informtion(ex.Message, 3);
                return false;
            }
           
                }
        

        public const int OF_READWRITE = 2;
        public const int OF_SHARE_DENY_NONE = 0x40;
        public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
       
        public  void DeleteFolder(object dir)
        {
            if (Directory.Exists(dir.ToString())) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir.ToString()))
                {
                    if (File.Exists(d))
                    {
                       
                        File.SetAttributes(d, FileAttributes.Normal);
                        File.Delete(d);
                        //直接删除其中的文件
                        /*for (int i=0;;i++ )
                        {
                            if (!File.Exists(d))
                            {
                                break;
                            }
                            try {
                                File.Delete(d);
                            }
                            catch  {
                                delete_file(Path.GetDirectoryName(d));
                                Delay(100);
                            }
                            
                            if (i > 10) {
                                File.Delete(d);
                            }
                            
                        }*/

                    }
                    else {
                        DeleteFolder(d);

                    }
                    //Application.DoEvents();
                }
                try
                {
                    Directory.Delete(dir.ToString(), true);
                }
                catch (Exception ee) { new_Show_Informtion(ee.Message, 3); }

            }
           
        }
        public void deleteUploadOaFolder(string folderPath)
        {
           
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(folderPath);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                System.IO.File.SetAttributes(folderPath, System.IO.FileAttributes.Normal);  //去除文件的只读属性
                if (Directory.Exists(folderPath))
                {
                    foreach (string f in Directory.GetFileSystemEntries(folderPath))
                    {
                        if (File.Exists(f))   //判断文件夹是否还存在
                        {
                            //如果有子文件删除文件
                            try
                            {
                                File.Delete(f);
                            }
                            catch (Exception ex)
                            {
                                delete_file(f);
                                File.Delete(f);
                            }
                           
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            deleteUploadOaFolder(f);
                        }
                    }
                    //删除空根文件夹。即传来一个文件夹如：/upload/kahnFolder/,则最后将根文件夹kahnFolder也删除掉
                    //Directory.Delete(folderPath);
                }
            }
            catch (Exception ex)  // 异常处理
            {
                Console.WriteLine(ex.Message.ToString());   // 异常信息
            }
        }
        Process process_delF;
        List<string> uid = new List<string>();
        List<string> jc_name = new List<string>();
        public void delete_file(string fileName) {
            string handle_32_64 = "";
            process_delF = new Process();
            if (Environment.Is64BitOperatingSystem)
            {
                handle_32_64 = @"\handel\handle64.exe";
            }
            else
            {
                handle_32_64 = @"\handel\handle.exe";
            }

            //System.Diagnostics.Process p = new System.Diagnostics.Process();
            //p.StartInfo = new System.Diagnostics.ProcessStartInfo(Environment.CurrentDirectory + handle_32_64);
            //p.Start();
            //p.WaitForExit();
            
            process_delF.StartInfo.FileName = Environment.CurrentDirectory + handle_32_64;
            process_delF.StartInfo.Arguments = string.Format("\"{0}\"", (fileName));
            process_delF.StartInfo.UseShellExecute = false;
            process_delF.StartInfo.RedirectStandardOutput = true;
            process_delF.StartInfo.CreateNoWindow = true;
            process_delF.Start(); 
            
            process_delF.WaitForExit();

            


            string outputTool = process_delF.StandardOutput.ReadToEnd();
            uid.Clear();
            string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
            //MessageBox.Show(outputTool);
            foreach (Match match in Regex.Matches(outputTool, matchPattern))
            {
                //Process.GetProcessById(int.Parse(match.Value)).Kill();
                //Process.GetProcessById(int.Parse(match.Value)).CloseMainWindow();
                if (!uid.Contains(match.Value))
                {
                    Process pro = Process.GetProcessById(int.Parse(match.Value));
                    pro.Kill();
                    uid.Add(match.Value);
                }
            }
        }
        public void delete_file_() {
            
            var pro = Process.GetProcesses(".");
            //将进程转化为 集合，并且筛选加排序
            var result = pro.OrderBy(p => p.ProcessName).Select(p => new { p.Id,  p.ProcessName, p.MainWindowTitle }).ToList();
            //int index = -1;
            result.ForEach((x) =>
            {
                int index = jc_name.FindIndex(kjc => kjc.ToUpper().IndexOf(x.ProcessName.ToUpper())>-1);
                if (index>-1)
                {
                    int id = Convert.ToInt32(x.Id);
                    Process prox = Process.GetProcessById(id);
                    prox.Kill();
                }
            });

            
            
        }
        
        [DllImport("kernel32.dll")]
        static extern uint GetTickCount();

        public void Delay(uint ms) 
        {
            uint start = GetTickCount();
            while (GetTickCount() - start < ms)
            {
                Application.DoEvents();
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Side.ToUpper() == "1"&&err==0)
            {
                e.Cancel = true; // 取消关闭操作
                return;
            }
            if (process_JY != null && !process_JY.HasExited)
            {
                process_JY.Kill();
            }
            if (process_YS != null && !process_YS.HasExited)
            {
                process_YS.Kill();
            }
            if (process_delF != null && !process_delF.HasExited)
            {
                process_delF.Kill();
            }
            //e.Cancel = true;
            StopProcess(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            
            //process_delF
            //System.Environment.Exit(0);
        }

        private void label1_Click(object sender, EventArgs e)
        {
            
            new_Show_Informtion(SET_PORT, 1); 
            new_Show_Informtion(Server_IP, 1);
            new_Show_Informtion(Server_PORT, 1);
            new_Show_Informtion(File_Name, 1);
            new_Show_Informtion(Save_Path, 1);
           
        }

        private void Form1_Shown(object sender, EventArgs e)
        {

            
            if (Side.ToUpper() == "1")
            {
                
                btnConnection_Click(sender, e);
                
            }


        }

        
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (Side.ToUpper() == "0") {
                if (this.WindowState == FormWindowState.Minimized) //如果窗体被最小化
                {
                    
                    this.notifyIcon1.Visible = true; //显示通知图标
                    this.notifyIcon1.Text = this.Text;
                    this.Visible = false;
                    //使Form不在任务栏上显示
                }
            }
                
        }
        
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (Side.ToUpper() == "0") {
                if (this.WindowState == FormWindowState.Minimized) //如果窗体被最小化
                {
                    this.Visible = true;
                    this.notifyIcon1.Visible = false;
                }
            }
                
        }

        private void Form1_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                //this.ShowInTaskbar = true;//使Form不在任务栏上显示

                this.WindowState = FormWindowState.Normal;
            }
            else
            { 
                //this.ShowInTaskbar = false; 
                this.WindowState = FormWindowState.Minimized; 
            }
        }
        public void DeleteFolder_(object dir)
        {
            if (Directory.Exists(dir.ToString())) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir.ToString()))
                {
                    if (File.Exists(d))
                    {
                        File.SetAttributes(d, FileAttributes.Normal);
                        File.Delete(d);
                    }
                    else
                    {
                        DeleteFolder_(d);
                    }
                    //Application.DoEvents();
                }
                try
                {
                    Directory.Delete(dir.ToString(), true);
                }
                catch (Exception ee) { new_Show_Informtion(ee.Message, 3); }

            }

        }
        private void button2_Click(object sender, EventArgs e)
        {
            //MessageBox.Show(deleteF(@"D:\新建文件夹\update").ToString());
            try
            {


                DeleteFolder_(@"D:\新建文件夹\update");

            }
            catch (Exception ex)
            {
                new_Show_Informtion(ex.Message, 3);
                
            }
            
            /*string filePath = "C:\\test.txt";

            // 设置文件属性为FILE_FLAG_DELETE_ON_CLOSE
            IntPtr handle = CreateFile(filePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal | FileAttributes.DeleteOnClose, IntPtr.Zero);

            if (handle != IntPtr.Zero && handle.ToInt32() != -1)
            {
                CloseHandle(handle);
            }
            else
            {
                // 文件无法打开，可能处于使用中状态，尝试重试或报错处理
            }*/


        }
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        static extern IntPtr CreateFile(string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool CloseHandle(IntPtr hObject);

        private void button2_Click_1(object sender, EventArgs e)
        {
            delete_file_();
        }

        private void button2_Click_2(object sender, EventArgs e)
        {
            File.Copy(Copy_Path, Paste_Path, true);
        }

        private void button2_Click_3(object sender, EventArgs e)
        {
            Extract_pok_(@"C:\Users\86183\Desktop\Microsoft.NETFramework4.rar");
        }
    }
}
