Помогите модифицировать код, для передачи больших файлов. Сервер: | Код | using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Xml.Serialization; using System.Diagnostics; using System.Threading; public class UdpFileServer { // Информация о файле (требуется для получателя) [Serializable] public class FileDetails { public string FILETYPE = ""; public long FILESIZE = 0; } private static FileDetails fileDet = new FileDetails(); // Поля, связанные с UdpClient private static IPAddress remoteIPAddress; private const int remotePort = 5002; private static UdpClient sender = new UdpClient(); private static IPEndPoint endPoint; // Filestream object private static FileStream fs; [STAThread] static void Main(string[] args) { try { // Получаем удаленный IP-адрес и создаем IPEndPoint // remoteIPAddress = IPAddress.Parse(Console.ReadLine().ToString());//"127.0.0.1"); remoteIPAddress = IPAddress.Parse("255.255.255.255".ToString()); endPoint = new IPEndPoint(remoteIPAddress, remotePort); Console.WriteLine("Удаленный IP-адрес: " + remoteIPAddress); // Получаем путь файла и его размер (должен быть меньше 8kb) Console.WriteLine("Введите путь к файлу и его имя"); fs = new FileStream(@Console.ReadLine().ToString(), FileMode.Open, FileAccess.Read); /* if (fs.Length > 8192) { Console.Write("Файл должен весить меньше 8кБ"); sender.Close(); fs.Close(); return; } * */ // Отправляем информацию о файле SendFileInfo(); // Ждем 2 секунды Thread.Sleep(2000); // Отправляем сам файл SendFile(); Console.ReadLine(); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } } public static void SendFileInfo() { // Получаем тип и расширение файла fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3); // Получаем длину файла fileDet.FILESIZE = fs.Length; XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails)); MemoryStream stream = new MemoryStream(); // Сериализуем объект fileSerializer.Serialize(stream, fileDet); // Считываем поток в байты stream.Position = 0; Byte[] bytes = new Byte[stream.Length]; stream.Read(bytes, 0, Convert.ToInt32(stream.Length)); Console.WriteLine("Отправка деталей файла..."); // Отправляем информацию о файле sender.Send(bytes, bytes.Length, endPoint); stream.Close(); } private static void SendFile() { // Создаем файловый поток и переводим его в байты long a; Byte[] bytes = new Byte[fs.Length]; long f_count = (int)fileDet.FILESIZE / 8192; Console.WriteLine("Отправка файла размером " + fs.Length + " байт"); if (fs.Length > 8192) { byte[] buffer = new byte[fs.Length]; while (true) { try { a = fs.Read(buffer, 0, buffer.Length); if (a == 0) { break; } sender.Send(buffer, buffer.Length, endPoint); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } } } else fs.Read(bytes, 0, bytes.Length); try { sender.Send(bytes, bytes.Length, endPoint); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } finally { fs.Close(); sender.Close(); } /* try { // Отправляем файл sender.Send(bytes, bytes.Length, endPoint); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } finally { // Закрываем соединение и очищаем поток fs.Close(); sender.Close(); } Console.WriteLine("Файл успешно отправлен."); Console.Read(); */ } }
|
Клиент: | Код | using System; using System.IO; using System.Net; using System.Diagnostics; using System.Net.Sockets; using System.Text; using System.Xml.Serialization; using System.Threading; public class UdpFileClient { // Детали файла [Serializable] public class FileDetails { public string FILETYPE = ""; public long FILESIZE = 0; } private static FileDetails fileDet; // Поля, связанные с UdpClient private static int localPort = 5002; private static UdpClient receivingUdpClient = new UdpClient(localPort); private static IPEndPoint RemoteIpEndPoint = null; private static FileStream fs; private static Byte[] receiveBytes = new Byte[0]; [STAThread] static void Main(string[] args) { // Получаем информацию о файле GetFileDetails(); // Получаем файл ReceiveFile(); } private static void GetFileDetails() { try { Console.WriteLine("-----------*******Ожидание информации о файле*******-----------"); // Получаем информацию о файле receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); Console.WriteLine("----Информация о файле получена!"); XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails)); MemoryStream stream1 = new MemoryStream(); // Считываем информацию о файле stream1.Write(receiveBytes, 0, receiveBytes.Length); stream1.Position = 0; // Вызываем метод Deserialize fileDet = (FileDetails)fileSerializer.Deserialize(stream1); Console.WriteLine("Получен файл типа ." + fileDet.FILETYPE + " имеющий размер " + fileDet.FILESIZE.ToString() + " байт"); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } } public static void ReceiveFile() { long a = 0; long f = (int)fileDet.FILESIZE; long x = fileDet.FILESIZE / 8192; string data = Encoding.ASCII.GetString(receiveBytes); if (fileDet.FILESIZE > 8192) { fs = new FileStream("temp." + fileDet.FILETYPE, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); while (true) { x--; try { receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); if(receiveBytes != null) { a = a + 1; } fs.Write(receiveBytes, 0, receiveBytes.Length); if (receiveBytes.Length < 8192) break; } catch (Exception eR) { Console.WriteLine(eR.ToString()); } finally { fs.Close(); receivingUdpClient.Close(); // Process.Start("Client.exe"); Console.Read(); } } } else try { Console.WriteLine("-----------*******Ожидайте получение файла*******-----------"); // Получаем файл receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); // Преобразуем и отображаем данные Console.WriteLine("----Файл получен...Сохраняем..."); // Создаем временный файл с полученным расширением fs = new FileStream("temp." + fileDet.FILETYPE, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); fs.Write(receiveBytes, 0, receiveBytes.Length); Console.WriteLine("----Файл сохранен..."); //Console.WriteLine("-------Открытие файла------"); // Открываем файл связанной с ним программой // Process.Start(fs.Name); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } finally { fs.Close(); receivingUdpClient.Close(); Process.Start("Client.exe"); //Console.Read(); } } }
|
|