MasstransferExporter/MasstransferInfrastructure/Process/Client/PipeClient.cs

82 lines
2.3 KiB
C#
Raw Normal View History

2024-09-03 08:13:49 +00:00
using System.IO.Pipes;
2024-09-04 02:11:04 +00:00
using MasstransferCommon.Utils;
2024-09-03 08:13:49 +00:00
namespace MasstransferCommunicate.Process.Client;
2024-09-04 02:11:04 +00:00
internal class PipeClient
2024-09-03 08:13:49 +00:00
{
private NamedPipeClientStream? _pipeClient;
2024-09-04 02:11:04 +00:00
private const string KeyPath = @"Software\Masstransfer\Security";
2024-09-03 08:13:49 +00:00
public event Action<string> MessageReceived;
/// <summary>
/// 启动连接
/// </summary>
public void Start()
{
Task.Run(ConnectToServer);
}
/// <summary>
/// 等待连接并监听信息
/// </summary>
private void ConnectToServer()
{
while (true)
{
try
{
2024-09-04 02:11:04 +00:00
Console.WriteLine("正在查找服务端管道id");
var pipeName = RegistryHelper.ReadValue(KeyPath, "PipeId");
if (pipeName == null)
{
Console.WriteLine("无法找到服务端管道id等待重试");
Thread.Sleep(1000);
continue;
}
_pipeClient = new NamedPipeClientStream(".", (string)pipeName, PipeDirection.InOut,
PipeOptions.Asynchronous);
2024-09-03 08:13:49 +00:00
Console.WriteLine("正在连接服务器");
_pipeClient.Connect(5000);
Console.WriteLine("已连接到服务器");
using var reader = new StreamReader(_pipeClient);
while (_pipeClient.IsConnected)
{
var message = reader.ReadLine();
if (message != null)
{
Console.WriteLine($"Received message: {message}");
MessageReceived?.Invoke(message);
}
}
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
finally
{
_pipeClient?.Dispose();
}
Thread.Sleep(1000); // Retry connection after delay
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="message"></param>
public void SendMessage(string message)
{
if (_pipeClient is { IsConnected: true })
{
var writer = new StreamWriter(_pipeClient) { AutoFlush = true };
writer.WriteLine(message);
}
}
}