Files
NetworkTest/Client/Program.cs
2025-09-17 11:07:45 +03:00

73 lines
2.1 KiB
C#

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Client;
using Domain;
using Domain.Dto;
using MessagePack;
if (args.Length < 2)
{
System.Console.WriteLine("Pass two args: http/tcp and json/bin");
return -1;
}
var protocol = args[0];
var serialization = args[1];
IClient? client = protocol switch
{
"http" => new HttpClientWrapper(serialization == "json" ? ConvertJsonResponse : ConvertMessagePackResponse),
"tcp" => new TcpClientWrapper(serialization == "json" ? ConvertBytesJson : ConvertBytesMessagePack),
_ => null
};
client?.Start();
System.Console.WriteLine("Client started:");
System.Console.WriteLine(client);
// Обработка выхода по Ctrl+C
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true; // Prevent immediate termination
Console.WriteLine("Shutdown signal received. Stopping client...");
client?.Stop();
Console.WriteLine("Goodbye!");
Environment.Exit(0);
};
// Бесконечный цикл ожидания
while (true)
{
Thread.Sleep(1000);
}
static async Task<Data?> ConvertJsonResponse(HttpResponseMessage response)
{
var json = await response.Content.ReadAsStringAsync();
var jsonData = JsonSerializer.Deserialize<JsonData>(json);
return jsonData?.ToData();
}
static async Task<Data?> ConvertMessagePackResponse(HttpResponseMessage response)
{
var bytes = await response.Content.ReadAsByteArrayAsync();
var msgPackData = MessagePackSerializer.Deserialize<MessagePackData>(bytes);
return msgPackData?.ToData();
}
static Task<Data?> ConvertBytesJson(byte[] bytes)
{
var json = Encoding.UTF8.GetString(bytes);
var jsonData = JsonSerializer.Deserialize<JsonData>(json);
return Task.FromResult(jsonData?.ToData());
}
static Task<Data?> ConvertBytesMessagePack(byte[] bytes)
{
var msgPackData = MessagePackSerializer.Deserialize<MessagePackData>(bytes);
return Task.FromResult(msgPackData?.ToData());
}