PipeStream.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace Xilium.CefGlue.Common.Shared.RendererProcessCommunication
  5. {
  6. internal class PipeStream
  7. {
  8. private readonly Stream _stream;
  9. private readonly UnicodeEncoding _streamEncoding;
  10. public PipeStream(Stream stream)
  11. {
  12. _stream = stream;
  13. _streamEncoding = new UnicodeEncoding();
  14. }
  15. public string ReadString()
  16. {
  17. var length = ReadInt(_stream);
  18. var buffer = new byte[length];
  19. _stream.Read(buffer, 0, buffer.Length);
  20. return _streamEncoding.GetString(buffer);
  21. }
  22. public void WriteString(string message)
  23. {
  24. var buffer = _streamEncoding.GetBytes(message);
  25. WriteInt(_stream, buffer.Length);
  26. _stream.Write(buffer, 0, buffer.Length);
  27. _stream.Flush();
  28. }
  29. private static int ReadInt(Stream stream)
  30. {
  31. var valueInBytes = new byte[4];
  32. for (var i = 0; i < valueInBytes.Length; i++)
  33. {
  34. valueInBytes[i] = (byte)stream.ReadByte();
  35. }
  36. return BitConverter.ToInt32(valueInBytes, 0);
  37. }
  38. private static int WriteInt(Stream stream, int value)
  39. {
  40. var valueInBytes = BitConverter.GetBytes(value);
  41. foreach (var @byte in valueInBytes)
  42. {
  43. stream.WriteByte(@byte);
  44. }
  45. return valueInBytes.Length;
  46. }
  47. }
  48. }