//
// NamedPipeClient.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Data;
using System.IO.Pipes;
using NosSmooth.Comms.Data;
using Remora.Results;
namespace NosSmooth.Comms.NamedPipes;
///
/// A client using named pipes.
///
public class NamedPipeClient : IClient
{
private readonly NamedPipeClientStream _stream;
///
/// Initializes a new instance of the class.
///
/// The name of the pipe.
public NamedPipeClient(string pipeName)
{
_stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
}
///
public ConnectionState State => _stream.IsConnected ? ConnectionState.Open : ConnectionState.Closed;
///
public Stream ReadStream => _stream;
///
public Stream WriteStream => _stream;
///
public void Disconnect()
{
_stream.Close();
_stream.Dispose();
}
///
public async Task ConnectAsync(CancellationToken ct)
{
try
{
await _stream.ConnectAsync(ct);
return Result.FromSuccess();
}
catch (OperationCanceledException)
{
// ignored
return Result.FromSuccess();
}
catch (Exception e)
{
return e;
}
}
}