Good morning everybody!! There is a client-server application in C #. Server:

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 Console.WriteLine("Введите удаленный IP-адрес"); remoteIPAddress = IPAddress.Parse(Console.ReadLine().ToString());//"127.0.0.1"); endPoint = new IPEndPoint(remoteIPAddress, remotePort); // Получаем путь файла и его размер (должен быть меньше 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() { // Создаем файловый поток и переводим его в байты Byte[] bytes = new Byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); Console.WriteLine("Отправка файла размером " + fs.Length + " байт"); try { // Отправляем файл sender.Send(bytes, bytes.Length, endPoint); } catch (Exception eR) { Console.WriteLine(eR.ToString()); } finally { // Закрываем соединение и очищаем поток fs.Close(); sender.Close(); } Console.WriteLine("Файл успешно отправлен."); Console.Read(); } } 

Customer:

 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() { 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(); Console.Read(); } } 

}

How to make it so that you can transfer files larger than 8kb? Please help

  • one
    Transfer portions of 8 KB? But TCP is better for this purpose. - free_ze
  • it turns out yes !! - Gerasimov Stanislav
  • Can I close the question?) - free_ze
  • if you want to transfer files by udp, then it is desirable to take the packet size less than udp. For a local network, this is somewhere 1500 bytes, for the entire Internet in the region of 500-600 bytes. Otherwise, the packets will be crushed and the likelihood that the whole package will run so far is small. - KoVadim
  • They said on UDP, do .. - Gerasimov Stanislav

0