MasstransferExporter/MasstransferInfrastructure/Process/Client/PipeClient.cs

82 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.IO.Pipes;
using MasstransferCommon.Utils;
namespace MasstransferCommunicate.Process.Client;
internal class PipeClient
{
private NamedPipeClientStream? _pipeClient;
private const string KeyPath = @"Software\Masstransfer\Security";
public event Action<string> MessageReceived;
/// <summary>
/// 启动连接
/// </summary>
public void Start()
{
Task.Run(ConnectToServer);
}
/// <summary>
/// 等待连接并监听信息
/// </summary>
private void ConnectToServer()
{
while (true)
{
try
{
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);
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);
}
}
}