189 lines
6.8 KiB
C#
189 lines
6.8 KiB
C#
using System;
|
||
using System.CommandLine;
|
||
using System.CommandLine.Parsing;
|
||
using System.Net.Sockets;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace f_cln
|
||
{
|
||
class Program
|
||
{
|
||
static async Task<int> Main(string[] args)
|
||
{
|
||
// Создание команды с аргументами
|
||
Option<string> ipOption = new("address", new[] { "--ip", "-i" })
|
||
{
|
||
Description = "IP адрес сервера (по умолчанию: localhost)",
|
||
DefaultValueFactory = parseResult => "localhost"
|
||
};
|
||
|
||
Option<int> portOption = new("port", new[] { "--port", "-p" })
|
||
{
|
||
Description = "Порт сервера (по умолчанию: 1771)",
|
||
DefaultValueFactory = parseResult => 1771
|
||
};
|
||
|
||
Option<string?> messageOption = new("message", new[] { "--message", "-m" })
|
||
{
|
||
Description = "Сообщение для отправки (если не указано, работает в интерактивном режиме)",
|
||
Arity = ArgumentArity.ZeroOrOne
|
||
};
|
||
|
||
var rootCommand = new RootCommand("Клиент для отправки строк серверу и получения их в обратном порядке")
|
||
{
|
||
ipOption,
|
||
portOption,
|
||
messageOption
|
||
};
|
||
|
||
ParseResult parseResult = rootCommand.Parse(args);
|
||
if (parseResult.Errors.Count == 0)
|
||
{
|
||
string ip = parseResult.GetValue(ipOption) ?? "localhost";
|
||
int port = parseResult.GetValue(portOption);
|
||
string? message = parseResult.GetValue(messageOption);
|
||
|
||
try
|
||
{
|
||
if (!string.IsNullOrEmpty(message))
|
||
{
|
||
// Режим однократной отправки
|
||
await SendMessage(ip, port, message);
|
||
}
|
||
else
|
||
{
|
||
// Интерактивный режим
|
||
await RunInteractive(ip, port);
|
||
}
|
||
|
||
return 0;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.Error.WriteLine($"Ошибка: {ex.Message}");
|
||
return 2;
|
||
}
|
||
}
|
||
else
|
||
{
|
||
foreach (ParseError parseError in parseResult.Errors)
|
||
{
|
||
Console.Error.WriteLine(parseError.Message);
|
||
}
|
||
return 1;
|
||
}
|
||
}
|
||
|
||
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 };
|
||
|
||
// Отправка сообщения
|
||
await writer.WriteLineAsync(message);
|
||
Console.WriteLine($"Отправлено: {message}");
|
||
|
||
// Чтение ответа
|
||
var response = await reader.ReadLineAsync();
|
||
|
||
if (response != null)
|
||
{
|
||
Console.WriteLine($"Получено: {response}");
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine("Сервер не ответил");
|
||
}
|
||
}
|
||
catch (SocketException ex)
|
||
{
|
||
Console.WriteLine($"Сетевая ошибка: {ex.Message}");
|
||
throw;
|
||
}
|
||
}
|
||
|
||
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 };
|
||
|
||
{
|
||
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))
|
||
{
|
||
Console.WriteLine("Завершение работы...");
|
||
break;
|
||
}
|
||
|
||
try
|
||
{
|
||
// Отправка сообщения
|
||
await writer.WriteLineAsync(input);
|
||
|
||
// Чтение ответа
|
||
var response = await reader.ReadLineAsync();
|
||
|
||
if (response != null)
|
||
{
|
||
Console.WriteLine($"Ответ: {response}");
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine("Сервер отключился");
|
||
break;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
Console.WriteLine($"Ошибка при отправке/получении: {ex.Message}");
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
catch (SocketException ex)
|
||
{
|
||
Console.WriteLine($"Ошибка подключения: {ex.Message}");
|
||
}
|
||
}
|
||
}
|
||
} |