check errors
This commit is contained in:
213
f-cln/Program.cs
213
f-cln/Program.cs
@@ -1,6 +1,7 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.CommandLine;
|
using System.CommandLine;
|
||||||
using System.CommandLine.Parsing;
|
using System.CommandLine.Parsing;
|
||||||
|
using System.IO;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -49,15 +50,13 @@ namespace f_cln
|
|||||||
if (!string.IsNullOrEmpty(message))
|
if (!string.IsNullOrEmpty(message))
|
||||||
{
|
{
|
||||||
// Режим однократной отправки
|
// Режим однократной отправки
|
||||||
await SendMessage(ip, port, message);
|
return await SendMessage(ip, port, message);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Интерактивный режим
|
// Интерактивный режим
|
||||||
await RunInteractive(ip, port);
|
return await RunInteractive(ip, port);
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -75,115 +74,165 @@ namespace f_cln
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async Task SendMessage(string ip, int port, string message)
|
static async Task<int> 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}...");
|
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 };
|
|
||||||
|
|
||||||
// Отправка сообщения
|
|
||||||
await writer.WriteLineAsync(message);
|
|
||||||
Console.WriteLine($"Отправлено: {message}");
|
|
||||||
|
|
||||||
// Чтение ответа
|
|
||||||
var response = await reader.ReadLineAsync();
|
|
||||||
|
|
||||||
if (response != null)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Получено: {response}");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.WriteLine("Сервер не ответил");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
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}");
|
string cleanedResponse = CleanInput(response);
|
||||||
throw;
|
Console.WriteLine($"Ответ: {cleanedResponse}");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine("Сервер не ответил");
|
||||||
|
return 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static async Task RunInteractive(string ip, int port)
|
static async Task<int> 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();
|
Console.WriteLine(); // Пустая строка для единообразия
|
||||||
await client.ConnectAsync(ip, port);
|
PrintHelp();
|
||||||
|
|
||||||
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 };
|
|
||||||
|
|
||||||
|
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("> ");
|
Console.Write("> ");
|
||||||
var input = Console.ReadLine();
|
var input = Console.ReadLine();
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(input))
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
continue;
|
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("Завершение работы...");
|
Console.WriteLine("Завершение работы...");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
if (input.Equals("help", StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
// Отправка сообщения
|
PrintHelp();
|
||||||
await writer.WriteLineAsync(input);
|
continue;
|
||||||
|
|
||||||
// Чтение ответа
|
|
||||||
var response = await reader.ReadLineAsync();
|
|
||||||
|
|
||||||
if (response != null)
|
|
||||||
{
|
|
||||||
Console.WriteLine($"Ответ: {response}");
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Console.WriteLine("Сервер отключился");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
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");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user