Пересылка файла через сокет - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день! Перейду сразу к делу - в нете полно примеров как пересылать файл с одной папки в другою через сокеты, но там один файл и все как-то просто. У меня задача посложнее: есть две папки, C:/server. C:/client ии я должен переслать все файлы с одной папки в другую, и наоборот (а если такой файл уже есть,то сравнить по дате какой файл позже сделан и его переместить вместо нового) (хотя этот пункт необязательно, мне бы просто переслать все файлы) Можно назвать это как файловый синхронизатор от одной папки на другую через сокет. Что я только не перепробовал, все равно не получается, вот надеюсь на добрую душу которая поможет, ибо я в отчаянье.

Решение задачи: «Пересылка файла через сокет»

textual
Листинг программы
  1. class Client
  2.     {
  3.  
  4.         private static string _serverPath = "C:/Socket/Server/";
  5.         private static string _clientPath = "C:/Socket/Client/";
  6.         private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  7.        
  8.         static void Main(string[] args)
  9.         {
  10.             Console.Title = "Client";
  11.             Connect();
  12.             TransferFiles();
  13.             Console.ReadLine();
  14.         }
  15.  
  16.        
  17.         private static void TransferFiles()
  18.         {
  19.             try
  20.             {
  21.                 if (!Directory.Exists(_clientPath) || !Directory.Exists(_serverPath))
  22.                 {
  23.                     ConsoleColor c = Console.ForegroundColor;
  24.                     Console.ForegroundColor = ConsoleColor.Red;
  25.                     Console.WriteLine(@"Create C:\Socket\Server and/or C:\Socket\client DIRECTORY!");
  26.                     Console.ForegroundColor = c;
  27.                 }
  28.                 else if (!Directory.EnumerateFileSystemEntries(_serverPath).Any() && !Directory.EnumerateFileSystemEntries(_clientPath).Any())
  29.                 {
  30.                     ConsoleColor c = Console.ForegroundColor;
  31.                     Console.ForegroundColor = ConsoleColor.Red;
  32.                     Console.WriteLine(@"Directories are empty!");
  33.                     Console.ForegroundColor = c;
  34.                 }
  35.                 else
  36.                 {
  37.                     while (true)
  38.                     {
  39.                         DirectoryInfo dir_server = new DirectoryInfo(_serverPath);
  40.                         foreach (var tempFile in dir_server.GetFiles())
  41.                         {
  42.                             string _fileName = tempFile.Name;
  43.                             byte[] buffer;
  44.                             if (!(File.Exists(_clientPath + _fileName)))
  45.                             {
  46.                                 Console.WriteLine("\tReceiving file: " + _fileName);
  47.                                 buffer = Encoding.ASCII.GetBytes(_fileName);
  48.                                 _clientSocket.Send(buffer);
  49.  
  50.                                 byte[] receivedBuf = new byte[1024];
  51.                                 int rec = _clientSocket.Receive(receivedBuf);
  52.                                 byte[] data = new byte[rec];
  53.                                 Array.Copy(receivedBuf, data, rec);
  54.  
  55.                                 string result = Encoding.ASCII.GetString(data);
  56.                                 ConsoleColor c = Console.ForegroundColor;
  57.                                 Console.ForegroundColor = ConsoleColor.DarkCyan;
  58.                                 Console.WriteLine("\t\t" + result + "\n");
  59.                                 Console.ForegroundColor = c;
  60.                             }
  61.                         }
  62.  
  63.                         DirectoryInfo dir_client = new DirectoryInfo(_clientPath);
  64.  
  65.                         foreach (var tempFile in dir_client.GetFiles())
  66.                         {
  67.                             string _fileName = tempFile.Name;
  68.                             byte[] buffer;
  69.                             if (!(File.Exists(_serverPath + _fileName)))
  70.                             {
  71.                                 Console.WriteLine("\tSending file: " + _fileName);
  72.  
  73.                                 buffer = Encoding.ASCII.GetBytes(_fileName);
  74.                                 _clientSocket.Send(buffer);
  75.  
  76.                                 byte[] receivedBuf = new byte[1024];
  77.                                 int rec = _clientSocket.Receive(receivedBuf);
  78.                                 byte[] data = new byte[rec];
  79.                                 Array.Copy(receivedBuf, data, rec);
  80.  
  81.                                 string result = Encoding.ASCII.GetString(data);
  82.                                 ConsoleColor c = Console.ForegroundColor;
  83.                                 Console.ForegroundColor = ConsoleColor.DarkCyan;
  84.                                 Console.WriteLine("\t\t" + result + "\n");
  85.                                 Console.ForegroundColor = c;
  86.                             }
  87.                             else //salidzina faila saturu
  88.                             {
  89.  
  90.                                 DirectoryInfo compare = new DirectoryInfo(_serverPath);
  91.                                 foreach (var temp in compare.GetFiles())
  92.                                 {
  93.                                     if (_fileName == temp.Name)
  94.                                     {
  95.                                         Console.WriteLine();
  96.                                         DateTime client_file_time = File.GetLastWriteTime(_clientPath + _fileName);
  97.                                         DateTime server_file_time = File.GetLastWriteTime(_serverPath + temp.Name);
  98.  
  99.                                         ConsoleColor c = Console.ForegroundColor;
  100.  
  101.                                         //clienta faila laika izvads:
  102.                                         Console.WriteLine("\n-----------------------------------------------------");
  103.                                         Console.ForegroundColor = ConsoleColor.Magenta;
  104.                                         Console.WriteLine("   There is equal files with name: " + _fileName);
  105.                                         Console.ForegroundColor = c;
  106.                                         Console.WriteLine("-----------------------------------------------------");
  107.                                         Console.Write("Client File name: ");
  108.                                         Console.ForegroundColor = ConsoleColor.Yellow;
  109.                                         Console.Write("\n" + _fileName);
  110.                                         Console.ForegroundColor = c;
  111.                                         Console.Write("\n" + "and it's creation time: ");
  112.                                         Console.ForegroundColor = ConsoleColor.Blue;
  113.                                         Console.Write(client_file_time);
  114.                                         Console.ForegroundColor = c;
  115.  
  116.                                         //servera faila laika izvads
  117.                                         Console.Write("\n\nServer File name: ");
  118.                                         Console.ForegroundColor = ConsoleColor.Yellow;
  119.                                         Console.Write("\n" + temp.Name);
  120.                                         Console.ForegroundColor = c;
  121.                                         Console.Write("\n" + "and it's creation time: ");
  122.                                         Console.ForegroundColor = ConsoleColor.Blue;
  123.                                         Console.Write(server_file_time);
  124.                                         Console.ForegroundColor = c;
  125.  
  126.  
  127.                                         Console.ForegroundColor = ConsoleColor.Cyan;
  128.                                         if (server_file_time > client_file_time)
  129.                                         {
  130.                                             Console.WriteLine("\n\n\t\tServer file is older!");
  131.                                             File.Delete(_clientPath + _fileName);
  132.                                             File.Copy(_serverPath + temp.Name, _clientPath + _fileName);
  133.                                             Console.ForegroundColor = ConsoleColor.Green;
  134.                                             Console.WriteLine("\n\tThe newest File has been replaced!");
  135.                                         }
  136.                                         else if (server_file_time == client_file_time)
  137.                                         {
  138.                                             Console.WriteLine("\n\n\t\tServer and Client files are equal");
  139.                                         }
  140.                                         else
  141.                                         {
  142.                                             Console.WriteLine("\n\n\t\tClient file is older");
  143.                                             File.Delete(_serverPath + temp.Name);
  144.                                             File.Copy(_clientPath + _fileName, _serverPath + temp.Name);
  145.                                             Console.ForegroundColor = ConsoleColor.Green;
  146.                                             Console.WriteLine("\n\tThe newest File has been replaced!");
  147.                                         }
  148.                                         Console.ForegroundColor = c;
  149.                                         Console.WriteLine("\n-----------------------------------------------------\n");
  150.                                     }
  151.                                 }
  152.                                 //Thread.Sleep(TimeSpan.FromMinutes(1)); //minutes intervals
  153.                                 Thread.Sleep(TimeSpan.FromSeconds(10)); //10 sekundes intervals
  154.                             }//else
  155.                         }
  156.                     }//while(true)
  157.                 }
  158.             }
  159.             catch (SocketException ex)
  160.             {
  161.                 Console.Clear();
  162.                 Console.WriteLine("\n\n\t\t\t\t    Server is closed!");
  163.                 System.Environment.Exit(1);
  164.             }
  165.         }
  166.  
  167.         private static void Connect()
  168.         {
  169.             int attempts = 0;
  170.             while (!_clientSocket.Connected)
  171.             {
  172.                 try
  173.                 {
  174.                     attempts++;
  175.                     _clientSocket.Connect(IPAddress.Loopback, 100);
  176.                 }  
  177.                 catch (SocketException ex)
  178.                 {
  179.                     Console.Clear();
  180.                     Console.WriteLine("\n\t\t\t     Connection attempts: " + attempts.ToString());
  181.                 }
  182.             }
  183.             Console.Clear();
  184.             ConsoleColor c = Console.ForegroundColor;
  185.             Console.ForegroundColor = ConsoleColor.DarkCyan;
  186.             Console.WriteLine();
  187.             Console.WriteLine("\t\t\t\tRaimonds Friidenbergs");
  188.             Console.WriteLine("\t\t\t\t\t3. kurss");
  189.             Console.WriteLine("\t\t\t\t\t  IT");
  190.             Console.WriteLine("\t\t   --------------------------------------------------");
  191.             Console.ForegroundColor = c;
  192.             Console.WriteLine("\n\t\t\t\tConnected successfuly!\n");
  193.         }
  194.     }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 3.333 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы