Esempio n. 1
0
        //Обработка отдельного соединения
        private void ProcessConnection(object state)
        {
            ConnectionInfo connection = (ConnectionInfo)state;
                try
                {

                    bool flag = true;
                    do
                    {
                        string cmd = connection.Reader.ReadString();

                        if (cmd.Contains(MessageClientServer.CONNECT))
                        {
                            try
                            {
                                string[] str = cmd.Split(' ');
                                connection.HostName = str[1];
                                Console.WriteLine("Соединение с {0} \n", connection.HostName);
                                SignalCool(connection);
                            }catch(Exception er)
                            {
                                Console.WriteLine(er.ToString());
                                SignalNoCool(connection);
                            }
                        }
                        else
                        {
                            if (cmd.Contains(MessageClientServer.START)) //Cигнал на загрузку файла
                            {
                                string[] str = cmd.Split(' ');
                                string uri = str[1];
                                int maxThread = Convert.ToInt32(str[2]);
                                Download d = new Download(uri,maxThread);
                                d.Proxy = this.proxy;
                                string filename = string.Empty;
                                d.FileName=MessageClientServer.GenerateFileNameFromUri(uri);
                                d.HostName = connection.HostName;
                                d.id = connection.id;
                                d.DownloadPath = d.DownloadPath + @"\"+d.FileName;
                                d.DownloadCompleted += DownloadCompleted;
                                d.DownloadProgressChanged += DownloadProgressChanged;
                                d.StatusChanged += StatusChanging;
                                d.BeginDownload();
                                sf.Add(d);

                                Console.WriteLine("{0}:Стартовать загрузку {1} \n", connection.HostName,uri);
                                StatusChanged(d);
                            }
                            else
                            {
                                if (cmd.Contains(MessageClientServer.LAST)) //Cигнал на загрузку имеющегося файла
                                {
                                    string[] str = cmd.Split(' ');
                                    string uri = str[1];
                                    for (int i = 0; i < sf.Count; i++)
                                    {
                                        if (sf[i].Url.AbsoluteUri == uri)
                                        {
                                            sf[i].BeginResume();
                                            Console.WriteLine("{0}:Стартовать имеющуюся загрузку {1} \n", connection.HostName, uri);
                                            StatusChanged(sf[i]);
                                        }
                                    }
                                }
                                else
                                {
                                    if (cmd.Contains(MessageClientServer.STOP)) //Стоп загрузки
                                    {
                                        string[] str = cmd.Split(' ');
                                        string uri = str[1];
                                        for (int i = 0; i < sf.Count; i++)
                                        {
                                            if (sf[i].Url.AbsoluteUri == uri)
                                            {
                                                sf[i].Cancel();
                                                Console.WriteLine("{0}:Остановить загрузку {1} \n", connection.HostName, uri);
                                               StatusChanged(sf[i]);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (cmd.Contains(MessageClientServer.PAUSE)) //Пауза загрузки
                                        {
                                            string[] str = cmd.Split(' ');
                                            string uri = str[1];
                                            for (int i = 0; i < sf.Count; i++)
                                            {
                                                if (sf[i].Url.AbsoluteUri == uri)
                                                {
                                                    sf[i].Pause();
                                                    Console.WriteLine("{0}:Приостановить загрузку {1} \n", connection.HostName, uri);
                                                    StatusChanged(sf[i]);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (cmd.Contains(MessageClientServer.DELETE)) //Удаление
                                            {
                                                string[] str = cmd.Split(' ');
                                                string uri = str[1];
                                                int[] tmp = new int[sf.Count];
                                                int k = 0;
                                                for (int i = 0; i < tmp.Length; i++)
                                                    tmp[i] = -1;
                                                for (int i = 0; i < sf.Count; i++)
                                                {
                                                    if (sf[i].Url.AbsoluteUri == uri && sf[i].HostName == connection.HostName)
                                                    {
                                                        try
                                                        {
                                                            if (File.Exists(sf[i].DownloadPath))
                                                                File.Delete(sf[i].DownloadPath);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Console.WriteLine("Невозможно удалить файл | " + ex.Message);
                                                        }
                                                        // sf[i].Cancel();
                                                        Console.WriteLine("{0}:Удалить загрузку {1} \n", connection.HostName, uri);
                                                        tmp[k] = i; k++;
                                                    }
                                                }
                                                if (tmp != null)
                                                {
                                                    for (int i = tmp.Length - 1; i >= 0; i--)
                                                    {
                                                        if (tmp[i] != -1)
                                                        {
                                                                sf.RemoveAt(tmp[i]);
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                switch (cmd)
                                                {
                                                    //Хост разрывает соединение
                                                    case MessageClientServer.CLOSE_CONNECT:
                                                        {
                                                            Console.WriteLine("Клиент {0} отключился.", connection.HostName);
                                                            flag = false;
                                                            break;
                                                        }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    } while (flag && connection.Socket.Connected);
                }
                catch (SocketException exp)
                {
                    Console.WriteLine(string.Format("SocketException на хосте: {0} - {1}", connection.HostName, exp.Message));
                }
                catch (Exception exp)
                {
                    Console.WriteLine(string.Format("Exception на хосте: {0} - {1}", connection.HostName, exp.Message));
                }
                finally
                {
                    connection.Writer.Close();
                    connection.Reader.Close();
                    connection.Stream.Close();
                    connection.Socket.Close();
                    lock (_connections)
                        _connections.Remove(connection);
                    SaveDownloadList("download.xml");
                }
        }
Esempio n. 2
0
        /// <summary>
        /// Загужает данные о закачке из xml файла
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>   
        public static Download FromXml(XmlReader reader)
        {
            Download result = new Download();

               reader.ReadStartElement("download");

               if (reader.Name != "uri") throw new FormatException();
               result.Url = new Uri(reader.ReadString());
               reader.Read();
               if (reader.Name != "filePath") throw new FormatException();

               string filePath = reader.ReadString();
               result.DownloadPath = Path.GetDirectoryName(filePath);
               result.FileName = Path.GetFileName(filePath);
               reader.Read();

               if (reader.Name != "size") throw new FormatException();
               result.TotalSize = Int64.Parse(reader.ReadString());
               reader.Read();
               if (reader.Name != "startpoint") throw new FormatException();
               result.StartPoint = long.Parse(reader.ReadString());
               reader.Read();
               if (reader.Name != "endpoint") throw new FormatException();
               result.EndPoint= long.Parse(reader.ReadString());
               reader.Read();
               if (reader.Name != "downloadState") throw new FormatException();
               result.Status = (StateDownload)(Convert.ToInt32(reader.ReadString()));
               //reader.Read();

               reader.ReadEndElement();
               return result;
        }
Esempio n. 3
0
        public static void StatusChanged(Download downloader)
        {
            switch (downloader.Status)
                {
                    case StateDownload.Downloading:
                        SignalFileDownload(downloader.HostName, downloader.id, downloader.Url.AbsoluteUri, downloader.TotalSize);
                        break;
                    case StateDownload.Stopped:
                        SignalStop(downloader.HostName, downloader.id, downloader.Url.AbsoluteUri,downloader.TotalSize);
                        break;
                    case StateDownload.Completed:
                        SignalCompleted(downloader.HostName, downloader.id, downloader.Url.AbsoluteUri, downloader.TotalSize);
                        break;
                    case StateDownload.Paused:
                        SignalPaused(downloader.HostName, downloader.id, downloader.Url.AbsoluteUri, downloader.TotalSize);
                        break;
                    case StateDownload.Nofile:
                        SignalNOFileDownload(downloader.HostName, downloader.id, downloader.Url.AbsoluteUri);
                        break;
                }

                if (downloader.Status == StateDownload.Paused)
                {
                    string tmp=
                       String.Format("Отправлено: {0}KB, Общий размер: {1}KB, Время: {2}:{3}:{4}",
                       downloader.DownloadedSize / 1024, downloader.TotalSize / 1024,
                       downloader.TotalUsedTime.Hours, downloader.TotalUsedTime.Minutes,
                       downloader.TotalUsedTime.Seconds);
                    Console.WriteLine(tmp+"\n");
                }
        }