FixedLengthFrameBuilder.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using MECF.Framework.Common.Communications.Tcp.Socket.Framing.Base;
  3. namespace MECF.Framework.Common.Communications.Tcp.Socket.Framing
  4. {
  5. public sealed class FixedLengthFrameBuilder : FrameBuilder
  6. {
  7. public FixedLengthFrameBuilder(int fixedFrameLength)
  8. : this(new FixedLengthFrameEncoder(fixedFrameLength), new FixedLengthFrameDecoder(fixedFrameLength))
  9. {
  10. }
  11. public FixedLengthFrameBuilder(FixedLengthFrameEncoder encoder, FixedLengthFrameDecoder decoder)
  12. : base(encoder, decoder)
  13. {
  14. }
  15. }
  16. public sealed class FixedLengthFrameEncoder : IFrameEncoder
  17. {
  18. private readonly int _fixedFrameLength;
  19. public FixedLengthFrameEncoder(int fixedFrameLength)
  20. {
  21. if (fixedFrameLength <= 0)
  22. throw new ArgumentOutOfRangeException("fixedFrameLength");
  23. _fixedFrameLength = fixedFrameLength;
  24. }
  25. public int FixedFrameLength { get { return _fixedFrameLength; } }
  26. public void EncodeFrame(byte[] payload, int offset, int count, out byte[] frameBuffer, out int frameBufferOffset, out int frameBufferLength)
  27. {
  28. if (count == FixedFrameLength)
  29. {
  30. frameBuffer = payload;
  31. frameBufferOffset = offset;
  32. frameBufferLength = count;
  33. }
  34. else
  35. {
  36. var buffer = new byte[FixedFrameLength];
  37. if (count >= FixedFrameLength)
  38. {
  39. Array.Copy(payload, offset, buffer, 0, FixedFrameLength);
  40. }
  41. else
  42. {
  43. Array.Copy(payload, offset, buffer, 0, count);
  44. for (int i = 0; i < FixedFrameLength - count; i++)
  45. {
  46. buffer[count + i] = (byte)'\n';
  47. }
  48. }
  49. frameBuffer = buffer;
  50. frameBufferOffset = 0;
  51. frameBufferLength = buffer.Length;
  52. }
  53. }
  54. }
  55. public sealed class FixedLengthFrameDecoder : IFrameDecoder
  56. {
  57. private readonly int _fixedFrameLength;
  58. public FixedLengthFrameDecoder(int fixedFrameLength)
  59. {
  60. if (fixedFrameLength <= 0)
  61. throw new ArgumentOutOfRangeException("fixedFrameLength");
  62. _fixedFrameLength = fixedFrameLength;
  63. }
  64. public int FixedFrameLength { get { return _fixedFrameLength; } }
  65. public bool TryDecodeFrame(byte[] buffer, int offset, int count, out int frameLength, out byte[] payload, out int payloadOffset, out int payloadCount)
  66. {
  67. frameLength = 0;
  68. payload = null;
  69. payloadOffset = 0;
  70. payloadCount = 0;
  71. if (count < FixedFrameLength)
  72. return false;
  73. frameLength = FixedFrameLength;
  74. payload = buffer;
  75. payloadOffset = offset;
  76. payloadCount = FixedFrameLength;
  77. return true;
  78. }
  79. }
  80. }