diff --git a/f-cln/Program.cs b/f-cln/Program.cs index da6008c..de0aa3a 100644 --- a/f-cln/Program.cs +++ b/f-cln/Program.cs @@ -1,6 +1,7 @@ using System; using System.CommandLine; using System.CommandLine.Parsing; +using System.IO; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; @@ -49,15 +50,13 @@ namespace f_cln if (!string.IsNullOrEmpty(message)) { // Режим однократной отправки - await SendMessage(ip, port, message); + return await SendMessage(ip, port, message); } else { // Интерактивный режим - await RunInteractive(ip, port); + return await RunInteractive(ip, port); } - - return 0; } catch (Exception ex) { @@ -75,115 +74,165 @@ namespace f_cln } } - static async Task SendMessage(string ip, int port, string message) + static async Task SendMessage(string ip, int port, string message) { - try + Console.WriteLine($"Подключение к {ip}:{port}..."); + + using var client = new TcpClient(); + await client.ConnectAsync(ip, port); + + Console.WriteLine("Подключено к серверу"); + + using var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8); + using var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }; + + // Читаем приветственное сообщение + var welcomeMessage = await reader.ReadLineAsync(); + if (welcomeMessage != null && welcomeMessage.StartsWith("hello ")) { - Console.WriteLine($"Подключение к {ip}:{port}..."); - - using var client = new TcpClient(); - await client.ConnectAsync(ip, port); - - Console.WriteLine("Подключено к серверу"); - - using var stream = client.GetStream(); - using var reader = new StreamReader(stream, Encoding.UTF8); - using var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }; - - // Отправка сообщения - await writer.WriteLineAsync(message); - Console.WriteLine($"Отправлено: {message}"); - - // Чтение ответа - var response = await reader.ReadLineAsync(); - - if (response != null) - { - Console.WriteLine($"Получено: {response}"); - } - else - { - Console.WriteLine("Сервер не ответил"); - } + var clientAddress = welcomeMessage[6..]; + Console.WriteLine($"Ваш адрес: {clientAddress}"); } - catch (SocketException ex) + + // Очистка сообщения + string cleanedMessage = CleanInput(message); + Console.WriteLine(); + + // Отправка сообщения + await writer.WriteLineAsync(cleanedMessage); + Console.WriteLine($"Отправлено: {cleanedMessage}"); + + // Чтение ответа + var response = await reader.ReadLineAsync(); + + if (response != null) { - Console.WriteLine($"Сетевая ошибка: {ex.Message}"); - throw; + string cleanedResponse = CleanInput(response); + Console.WriteLine($"Ответ: {cleanedResponse}"); + return 0; + } + else + { + Console.WriteLine("Сервер не ответил"); + return 2; } } - static async Task RunInteractive(string ip, int port) + static async Task RunInteractive(string ip, int port) { - try + Console.WriteLine($"Подключение к {ip}:{port}..."); + + using var client = new TcpClient(); + await client.ConnectAsync(ip, port); + + Console.WriteLine("Подключено к серверу"); + + using var stream = client.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8); + using var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }; + + // Читаем приветственное сообщение + var welcomeMessage = await reader.ReadLineAsync(); + if (welcomeMessage != null && welcomeMessage.StartsWith("hello ")) { - Console.WriteLine($"Подключение к {ip}:{port}..."); + var clientAddress = welcomeMessage[6..]; + Console.WriteLine($"Ваш адрес: {clientAddress}"); + } - using var client = new TcpClient(); - await client.ConnectAsync(ip, port); - - Console.WriteLine("Подключено к серверу"); - - using var stream = client.GetStream(); - using var reader = new StreamReader(stream, Encoding.UTF8); - using var writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true }; + Console.WriteLine(); // Пустая строка для единообразия + PrintHelp(); + while (true) + { + try { - string? hello = reader.ReadLine(); - if (hello != null && hello.Length > 6) - { - hello = hello.Remove(0, 6); -// hello = hello.Replace("hello ", ""); - Console.WriteLine($"Локальный адрес: {hello}"); - } - } - - Console.WriteLine("Введите текст для отправки (или 'exit' для выхода):"); - - while (true) - { - // Чтение ввода пользователя Console.Write("> "); var input = Console.ReadLine(); if (string.IsNullOrWhiteSpace(input)) continue; - if (input.Equals("exit", StringComparison.OrdinalIgnoreCase)) + // Очистка ввода от непечатаемых символов и BOM + input = CleanInput(input); + + if (string.IsNullOrEmpty(input)) + continue; + + if (input.Equals("exit", StringComparison.OrdinalIgnoreCase) || + input.Equals("quit", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Завершение работы..."); break; } - try + if (input.Equals("help", StringComparison.OrdinalIgnoreCase)) { - // Отправка сообщения - await writer.WriteLineAsync(input); - - // Чтение ответа - var response = await reader.ReadLineAsync(); - - if (response != null) - { - Console.WriteLine($"Ответ: {response}"); - } - else - { - Console.WriteLine("Сервер отключился"); - break; - } + PrintHelp(); + continue; } - catch (Exception ex) + + // Отправка сообщения + await writer.WriteLineAsync(input); + Console.WriteLine($"Отправлено: {input}"); + + // Чтение ответа + var response = await reader.ReadLineAsync(); + + if (response != null) { - Console.WriteLine($"Ошибка при отправке/получении: {ex.Message}"); - break; + // Очистка ответа от непечатаемых символов + response = CleanInput(response); + Console.WriteLine($"Ответ: {response}"); + } + else + { + Console.WriteLine("Сервер отключился"); + return 2; } } + catch (Exception ex) when (ex is IOException || ex is ObjectDisposedException) + { + Console.WriteLine("Соединение с сервером разорвано"); + return 2; + } + catch (Exception ex) + { + Console.WriteLine($"Ошибка: {ex.Message}"); + return 2; + } } - catch (SocketException ex) + + return 0; + } + + // Метод для очистки строки от непечатаемых символов + static string CleanInput(string input) + { + if (string.IsNullOrEmpty(input)) + return input; + + // Удаляем BOM (U+FEFF) и другие непечатаемые символы + var result = new StringBuilder(); + foreach (char c in input) { - Console.WriteLine($"Ошибка подключения: {ex.Message}"); + // Оставляем только печатаемые символы и пробелы + if (!char.IsControl(c) || c == '\n' || c == '\r' || c == '\t') + { + result.Append(c); + } } + + return result.ToString().Trim(); + } + + static void PrintHelp() + { + Console.WriteLine("\n=== Команды клиента ==="); + Console.WriteLine(" Просто введите текст для отправки на сервер"); + Console.WriteLine(" exit или quit - завершить работу"); + Console.WriteLine(" help - показать эту справку"); + Console.WriteLine("========================\n"); } } } \ No newline at end of file