Files
RedisManager/RedisManagerClient.cs
GuilhermeStrice f37078157d add project
2025-07-09 19:31:34 +01:00

79 lines
3.0 KiB
C#

using System;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace RedisManager
{
/// <summary>
/// Client for communicating with the RedisManager service.
/// Connects to a running service instance and sends command requests over TCP.
/// </summary>
public class RedisManagerClient
{
private readonly string _host = "localhost";
private readonly int _port = 6380; // Same port as service
/// <summary>
/// Executes a Redis command by sending it to the RedisManager service.
/// Connects to the service, sends the command arguments, and displays the result.
/// </summary>
/// <param name="args">Command line arguments to execute on the service</param>
/// <returns>Exit code (0 for success, 1 for failure)</returns>
public async Task<int> ExecuteCommandAsync(string[] args)
{
try
{
using var client = new TcpClient();
await client.ConnectAsync(_host, _port);
var request = new ServiceRequest
{
Command = "execute",
Arguments = args
};
var requestJson = JsonSerializer.Serialize(request) + "\n";
using var stream = client.GetStream();
using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
await writer.WriteAsync(requestJson);
using var reader = new StreamReader(stream, new UTF8Encoding(false));
var responseJson = await reader.ReadLineAsync();
if (responseJson != null)
{
var serviceResponse = JsonSerializer.Deserialize<ServiceResponse>(responseJson);
if (serviceResponse.Success)
{
Console.WriteLine(serviceResponse.Data);
return 0;
}
else
{
Console.WriteLine($"Error: {serviceResponse.Error}");
if (!string.IsNullOrEmpty(serviceResponse.ErrorCode))
Console.WriteLine($"Error Code: {serviceResponse.ErrorCode}");
if (serviceResponse.ErrorDetails != null)
Console.WriteLine($"Error Details: {JsonSerializer.Serialize(serviceResponse.ErrorDetails)}");
return 1;
}
}
Console.WriteLine("No response from service");
return 1;
}
catch (SocketException)
{
// Special code to indicate the service is not running
return 2;
}
catch (Exception ex)
{
Console.WriteLine($"Error communicating with service: {ex.Message}");
return 1;
}
}
}
}