using BBWY.Common.Models; using System; using System.Collections.Generic; using System.IO; using System.IO.Pipes; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BBWY.Client.Helpers { public class PipeHelper: IDenpendency { public PipeHelper() { _pipeServerDictionary = new Dictionary(); } private IDictionary _pipeServerDictionary; public Action ServerReceiveCallback; private async Task WaitForClientConnectionsAsync(NamedPipeServerStream pipeServer) { while (true) { await pipeServer.WaitForConnectionAsync().ConfigureAwait(false); try { const int bufferLength = 1024; var buffer = new byte[bufferLength]; using (var stream = new MemoryStream()) { while (true) { var bytesRead = await pipeServer.ReadAsync(buffer.AsMemory(0, bufferLength), CancellationToken.None).ConfigureAwait(false); if (bytesRead == 0) { break; } stream.Write(buffer, 0, bytesRead); } stream.Seek(0, SeekOrigin.Begin); ServerReceiveCallback?.Invoke(Encoding.UTF8.GetString(stream.ToArray())); } } finally { pipeServer.Disconnect(); } } } public void CreateServer(string pipeName) { var _pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); _ = WaitForClientConnectionsAsync(_pipeServer); } public void CloseServer(string pipeName) { if (_pipeServerDictionary.TryGetValue(pipeName, out NamedPipeServerStream pipeServer)) { try { pipeServer.Disconnect(); pipeServer.Dispose(); pipeServer.Close(); _pipeServerDictionary.Remove(pipeName); } catch (Exception ex) { } } } } }