Message.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MSHO.Collection.Service.IO
  7. {
  8. public class Message
  9. {
  10. public Message() { }
  11. public Message(Msg msg) {
  12. this.Content = JsonSerializable.ToJson(msg);
  13. }
  14. public Encoding Encoding {
  15. get { return Encoding.UTF8; }
  16. }
  17. public long Length {
  18. get {
  19. if (this.Stream != null) {
  20. return this.Stream.Length;
  21. }
  22. return 0;
  23. }
  24. }
  25. public System.IO.MemoryStream Stream { get; set; }
  26. /// <summary>
  27. /// 错误的消息
  28. /// </summary>
  29. public bool BadMsg { get; set; }
  30. public string Content {
  31. get {
  32. if (this.Stream != null)
  33. {
  34. return this.Encoding.GetString(this.Stream.ToArray());
  35. }
  36. return null;
  37. }
  38. set {
  39. if (value != null)
  40. {
  41. var buffer = this.Encoding.GetBytes(value);
  42. if (this.Stream == null) { this.Stream = new System.IO.MemoryStream(); }
  43. this.Stream.Write(buffer, 0, buffer.Length);
  44. }
  45. else {
  46. this.Stream = null;
  47. }
  48. }
  49. }
  50. public byte[] ToBuffer()
  51. {
  52. var mem = new System.IO.MemoryStream();
  53. var buffer = Helper.LongToBytes(this.Length);
  54. mem.Write(buffer, 0, buffer.Length);
  55. if (!string.IsNullOrEmpty(this.Content))
  56. {
  57. buffer = Encoding.UTF8.GetBytes(this.Content);
  58. mem.Write(buffer, 0, buffer.Length);
  59. }
  60. return mem.ToArray();
  61. }
  62. public void FromStream(System.IO.MemoryStream stream) {
  63. if (stream != null) {
  64. var buffer = new byte[sizeof(long)];
  65. var len = stream.Read(buffer, 0, buffer.Length);
  66. if (len == sizeof(long)) {
  67. var length = Helper.BytesToLong(buffer);
  68. buffer = new byte[length];
  69. len = stream.Read(buffer, 0, (int)length);
  70. this.Content = this.Encoding.GetString(buffer);
  71. }
  72. }
  73. }
  74. public void Write(byte[] buffer, int pos, int size) {
  75. if (Stream == null) {
  76. Stream = new System.IO.MemoryStream();
  77. }
  78. Stream.Write(buffer, pos, size);
  79. }
  80. public void Write(byte[] buffer)
  81. {
  82. if (Stream == null)
  83. {
  84. Stream = new System.IO.MemoryStream();
  85. }
  86. Stream.Write(buffer, 0, buffer.Length);
  87. }
  88. }
  89. }