using System;
|
using System.IO;
|
using System.IO.Pipes;
|
using System.Threading;
|
using System.Threading.Tasks;
|
|
namespace ConnectionUtil
|
{
|
public class PipeClient : IDisposable
|
{
|
private readonly string _pipeName;
|
private readonly string _serverName;
|
private readonly CancellationTokenSource _cancellationTokenSource;
|
private NamedPipeClientStream _pipeClient;
|
private bool _isDisposed;
|
private bool _isConnected;
|
private readonly object _sendLock = new object();
|
|
// 事件定义
|
public event EventHandler<PipeDataEventArgs> OnData;
|
public event EventHandler OnConnected;
|
public event EventHandler OnDisconnected;
|
|
public PipeClient(string pipeName, string serverName = ".")
|
{
|
_pipeName = pipeName;
|
_serverName = serverName;
|
_cancellationTokenSource = new CancellationTokenSource();
|
}
|
|
public void Connect(int timeoutMs = 5000)
|
{
|
if (_isConnected)
|
return;
|
_pipeClient = new NamedPipeClientStream(_pipeName);
|
|
_pipeClient.Connect(timeoutMs);
|
_pipeClient.ReadMode = PipeTransmissionMode.Message;
|
_isConnected = true;
|
Console.WriteLine("连接成功!");
|
|
// 触发连接成功事件
|
OnConnected?.Invoke(this, EventArgs.Empty);
|
}
|
|
public bool SendMessage(string message, out string response, int timeoutMs = 5000)
|
{
|
if (!_isConnected)
|
{
|
response = "客户端未连接到服务器";
|
return false;
|
}
|
response = null;
|
lock (_sendLock)
|
{
|
try
|
{
|
// 发送消息
|
_pipeClient.WriteMessage(message);
|
return true;
|
while (_isConnected && !_cancellationTokenSource.Token.IsCancellationRequested)
|
{
|
try
|
{
|
response = _pipeClient.ReadMessage();
|
break;
|
}
|
catch (Exception ex)
|
{
|
Console.WriteLine($"接收数据时发生错误: {ex.Message}");
|
break;
|
}
|
}
|
return true;
|
}
|
catch (Exception ex)
|
{
|
return false;
|
}
|
}
|
}
|
|
public void Disconnect()
|
{
|
_isConnected = false;
|
_cancellationTokenSource.Cancel();
|
}
|
|
public void Dispose()
|
{
|
if (!_isDisposed)
|
{
|
Disconnect();
|
_pipeClient?.Dispose();
|
_cancellationTokenSource.Dispose();
|
_isDisposed = true;
|
}
|
}
|
}
|
}
|