using System; using System.Net.Sockets; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace RedisManager { /// /// Client for communicating with the RedisManager service. /// Connects to a running service instance and sends command requests over TCP. /// public class RedisManagerClient { private readonly string _host = "localhost"; private readonly int _port = 6380; // Same port as service /// /// Executes a Redis command by sending it to the RedisManager service. /// Connects to the service, sends the command arguments, and displays the result. /// /// Command line arguments to execute on the service /// Exit code (0 for success, 1 for failure) public async Task 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(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; } } } }