add project
This commit is contained in:
79
RedisManagerClient.cs
Normal file
79
RedisManagerClient.cs
Normal file
@ -0,0 +1,79 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user