PipeServer.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.IO;
  3. using System.IO.Pipes;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. namespace Xilium.CefGlue.Common.Shared.RendererProcessCommunication
  7. {
  8. internal class PipeServer : IDisposable
  9. {
  10. private const int MaxErrorsAllowed = 5;
  11. private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
  12. public event Action<string> MessageReceived;
  13. public PipeServer(string pipeName)
  14. {
  15. Task.Run(async () =>
  16. {
  17. var errorCount = 0;
  18. while (!_cancellationTokenSource.IsCancellationRequested)
  19. {
  20. try
  21. {
  22. using (var serverPipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
  23. {
  24. await serverPipe.WaitForConnectionAsync(_cancellationTokenSource.Token);
  25. HandleClientConnected(serverPipe);
  26. }
  27. }
  28. catch
  29. {
  30. errorCount++;
  31. if (errorCount > MaxErrorsAllowed)
  32. {
  33. break;
  34. }
  35. }
  36. }
  37. });
  38. }
  39. public void Dispose()
  40. {
  41. _cancellationTokenSource.Cancel();
  42. }
  43. private void HandleClientConnected(Stream pipe)
  44. {
  45. var messageReceivedHandler = MessageReceived;
  46. if (messageReceivedHandler == null)
  47. {
  48. return;
  49. }
  50. var stream = new PipeStream(pipe);
  51. var message = stream.ReadString();
  52. messageReceivedHandler(message);
  53. }
  54. }
  55. }