check errors

This commit is contained in:
ascet-tomsk
2026-01-19 02:24:04 +07:00
parent 634ad7e14f
commit 824e816440

View File

@@ -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,9 +74,7 @@ namespace f_cln
}
}
static async Task SendMessage(string ip, int port, string message)
{
try
static async Task<int> SendMessage(string ip, int port, string message)
{
Console.WriteLine($"Подключение к {ip}:{port}...");
@@ -90,32 +87,39 @@ namespace f_cln
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 "))
{
var clientAddress = welcomeMessage[6..];
Console.WriteLine($"Ваш адрес: {clientAddress}");
}
// Очистка сообщения
string cleanedMessage = CleanInput(message);
Console.WriteLine();
// Отправка сообщения
await writer.WriteLineAsync(message);
Console.WriteLine($"Отправлено: {message}");
await writer.WriteLineAsync(cleanedMessage);
Console.WriteLine($"Отправлено: {cleanedMessage}");
// Чтение ответа
var response = await reader.ReadLineAsync();
if (response != null)
{
Console.WriteLine($"Получено: {response}");
string cleanedResponse = CleanInput(response);
Console.WriteLine($"Ответ: {cleanedResponse}");
return 0;
}
else
{
Console.WriteLine("Сервер не ответил");
}
}
catch (SocketException ex)
{
Console.WriteLine($"Сетевая ошибка: {ex.Message}");
throw;
return 2;
}
}
static async Task RunInteractive(string ip, int port)
{
try
static async Task<int> RunInteractive(string ip, int port)
{
Console.WriteLine($"Подключение к {ip}:{port}...");
@@ -128,62 +132,107 @@ namespace f_cln
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 "))
{
string? hello = reader.ReadLine();
if (hello != null && hello.Length > 6)
{
hello = hello.Remove(0, 6);
// hello = hello.Replace("hello ", "");
Console.WriteLine($"Локальный адрес: {hello}");
}
var clientAddress = welcomeMessage[6..];
Console.WriteLine($"Ваш адрес: {clientAddress}");
}
Console.WriteLine("Введите текст для отправки (или 'exit' для выхода):");
Console.WriteLine(); // Пустая строка для единообразия
PrintHelp();
while (true)
{
// Чтение ввода пользователя
try
{
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))
{
PrintHelp();
continue;
}
// Отправка сообщения
await writer.WriteLineAsync(input);
Console.WriteLine($"Отправлено: {input}");
// Чтение ответа
var response = await reader.ReadLineAsync();
if (response != null)
{
// Очистка ответа от непечатаемых символов
response = CleanInput(response);
Console.WriteLine($"Ответ: {response}");
}
else
{
Console.WriteLine("Сервер отключился");
break;
return 2;
}
}
catch (Exception ex) when (ex is IOException || ex is ObjectDisposedException)
{
Console.WriteLine("Соединение с сервером разорвано");
return 2;
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при отправке/получении: {ex.Message}");
break;
Console.WriteLine($"Ошибка: {ex.Message}");
return 2;
}
}
return 0;
}
catch (SocketException ex)
// Метод для очистки строки от непечатаемых символов
static string CleanInput(string input)
{
Console.WriteLine($"Ошибка подключения: {ex.Message}");
if (string.IsNullOrEmpty(input))
return input;
// Удаляем BOM (U+FEFF) и другие непечатаемые символы
var result = new StringBuilder();
foreach (char c in input)
{
// Оставляем только печатаемые символы и пробелы
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");
}
}
}