Пересылка файла через сокет - C#
Формулировка задачи:
Добрый день!
Перейду сразу к делу - в нете полно примеров как пересылать файл с одной папки в другою через сокеты, но там один файл и все как-то просто.
У меня задача посложнее: есть две папки, C:/server. C:/client ии я должен переслать все файлы с одной папки в другую, и наоборот (а если такой файл уже есть,то сравнить по дате какой файл позже сделан и его переместить вместо нового) (хотя этот пункт необязательно, мне бы просто переслать все файлы)
Можно назвать это как файловый синхронизатор от одной папки на другую через сокет.
Что я только не перепробовал, все равно не получается, вот надеюсь на добрую душу которая поможет, ибо я в отчаянье.
Решение задачи: «Пересылка файла через сокет»
textual
Листинг программы
- class Client
- {
- private static string _serverPath = "C:/Socket/Server/";
- private static string _clientPath = "C:/Socket/Client/";
- private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- static void Main(string[] args)
- {
- Console.Title = "Client";
- Connect();
- TransferFiles();
- Console.ReadLine();
- }
- private static void TransferFiles()
- {
- try
- {
- if (!Directory.Exists(_clientPath) || !Directory.Exists(_serverPath))
- {
- ConsoleColor c = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine(@"Create C:\Socket\Server and/or C:\Socket\client DIRECTORY!");
- Console.ForegroundColor = c;
- }
- else if (!Directory.EnumerateFileSystemEntries(_serverPath).Any() && !Directory.EnumerateFileSystemEntries(_clientPath).Any())
- {
- ConsoleColor c = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine(@"Directories are empty!");
- Console.ForegroundColor = c;
- }
- else
- {
- while (true)
- {
- DirectoryInfo dir_server = new DirectoryInfo(_serverPath);
- foreach (var tempFile in dir_server.GetFiles())
- {
- string _fileName = tempFile.Name;
- byte[] buffer;
- if (!(File.Exists(_clientPath + _fileName)))
- {
- Console.WriteLine("\tReceiving file: " + _fileName);
- buffer = Encoding.ASCII.GetBytes(_fileName);
- _clientSocket.Send(buffer);
- byte[] receivedBuf = new byte[1024];
- int rec = _clientSocket.Receive(receivedBuf);
- byte[] data = new byte[rec];
- Array.Copy(receivedBuf, data, rec);
- string result = Encoding.ASCII.GetString(data);
- ConsoleColor c = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.DarkCyan;
- Console.WriteLine("\t\t" + result + "\n");
- Console.ForegroundColor = c;
- }
- }
- DirectoryInfo dir_client = new DirectoryInfo(_clientPath);
- foreach (var tempFile in dir_client.GetFiles())
- {
- string _fileName = tempFile.Name;
- byte[] buffer;
- if (!(File.Exists(_serverPath + _fileName)))
- {
- Console.WriteLine("\tSending file: " + _fileName);
- buffer = Encoding.ASCII.GetBytes(_fileName);
- _clientSocket.Send(buffer);
- byte[] receivedBuf = new byte[1024];
- int rec = _clientSocket.Receive(receivedBuf);
- byte[] data = new byte[rec];
- Array.Copy(receivedBuf, data, rec);
- string result = Encoding.ASCII.GetString(data);
- ConsoleColor c = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.DarkCyan;
- Console.WriteLine("\t\t" + result + "\n");
- Console.ForegroundColor = c;
- }
- else //salidzina faila saturu
- {
- DirectoryInfo compare = new DirectoryInfo(_serverPath);
- foreach (var temp in compare.GetFiles())
- {
- if (_fileName == temp.Name)
- {
- Console.WriteLine();
- DateTime client_file_time = File.GetLastWriteTime(_clientPath + _fileName);
- DateTime server_file_time = File.GetLastWriteTime(_serverPath + temp.Name);
- ConsoleColor c = Console.ForegroundColor;
- //clienta faila laika izvads:
- Console.WriteLine("\n-----------------------------------------------------");
- Console.ForegroundColor = ConsoleColor.Magenta;
- Console.WriteLine(" There is equal files with name: " + _fileName);
- Console.ForegroundColor = c;
- Console.WriteLine("-----------------------------------------------------");
- Console.Write("Client File name: ");
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.Write("\n" + _fileName);
- Console.ForegroundColor = c;
- Console.Write("\n" + "and it's creation time: ");
- Console.ForegroundColor = ConsoleColor.Blue;
- Console.Write(client_file_time);
- Console.ForegroundColor = c;
- //servera faila laika izvads
- Console.Write("\n\nServer File name: ");
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.Write("\n" + temp.Name);
- Console.ForegroundColor = c;
- Console.Write("\n" + "and it's creation time: ");
- Console.ForegroundColor = ConsoleColor.Blue;
- Console.Write(server_file_time);
- Console.ForegroundColor = c;
- Console.ForegroundColor = ConsoleColor.Cyan;
- if (server_file_time > client_file_time)
- {
- Console.WriteLine("\n\n\t\tServer file is older!");
- File.Delete(_clientPath + _fileName);
- File.Copy(_serverPath + temp.Name, _clientPath + _fileName);
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine("\n\tThe newest File has been replaced!");
- }
- else if (server_file_time == client_file_time)
- {
- Console.WriteLine("\n\n\t\tServer and Client files are equal");
- }
- else
- {
- Console.WriteLine("\n\n\t\tClient file is older");
- File.Delete(_serverPath + temp.Name);
- File.Copy(_clientPath + _fileName, _serverPath + temp.Name);
- Console.ForegroundColor = ConsoleColor.Green;
- Console.WriteLine("\n\tThe newest File has been replaced!");
- }
- Console.ForegroundColor = c;
- Console.WriteLine("\n-----------------------------------------------------\n");
- }
- }
- //Thread.Sleep(TimeSpan.FromMinutes(1)); //minutes intervals
- Thread.Sleep(TimeSpan.FromSeconds(10)); //10 sekundes intervals
- }//else
- }
- }//while(true)
- }
- }
- catch (SocketException ex)
- {
- Console.Clear();
- Console.WriteLine("\n\n\t\t\t\t Server is closed!");
- System.Environment.Exit(1);
- }
- }
- private static void Connect()
- {
- int attempts = 0;
- while (!_clientSocket.Connected)
- {
- try
- {
- attempts++;
- _clientSocket.Connect(IPAddress.Loopback, 100);
- }
- catch (SocketException ex)
- {
- Console.Clear();
- Console.WriteLine("\n\t\t\t Connection attempts: " + attempts.ToString());
- }
- }
- Console.Clear();
- ConsoleColor c = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.DarkCyan;
- Console.WriteLine();
- Console.WriteLine("\t\t\t\tRaimonds Friidenbergs");
- Console.WriteLine("\t\t\t\t\t3. kurss");
- Console.WriteLine("\t\t\t\t\t IT");
- Console.WriteLine("\t\t --------------------------------------------------");
- Console.ForegroundColor = c;
- Console.WriteLine("\n\t\t\t\tConnected successfuly!\n");
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д