TcpDataModel.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using Azylee.Core.DataUtils.SerializeUtils;
  2. using Azylee.Core.WindowsUtils.ConsoleUtils;
  3. using Azylee.Jsons;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Azylee.YeahWeb.SocketUtils.TcpUtils
  9. {
  10. /// <summary>
  11. /// Tcp 传输数据模型
  12. /// </summary>
  13. public class TcpDataModel
  14. {
  15. /// <summary>
  16. /// 类型
  17. /// </summary>
  18. public int Type { get; set; }
  19. /// <summary>
  20. /// 数据
  21. /// </summary>
  22. public byte[] Data { get; set; }
  23. /// <summary>
  24. /// 默认构造函数
  25. /// </summary>
  26. public TcpDataModel() { }
  27. /// <summary>
  28. /// 构造函数(仅指令)
  29. /// </summary>
  30. /// <param name="type"></param>
  31. public TcpDataModel(int type)
  32. {
  33. this.Type = type;
  34. }
  35. /// <summary>
  36. /// 构造函数(默认)
  37. /// </summary>
  38. /// <param name="type"></param>
  39. /// <param name="data"></param>
  40. public TcpDataModel(int type, byte[] data)
  41. {
  42. this.Type = type;
  43. this.Data = data;
  44. }
  45. /// <summary>
  46. /// 构造函数(自动转换)
  47. /// </summary>
  48. /// <param name="type"></param>
  49. /// <param name="data"></param>
  50. public TcpDataModel(int type, object data)
  51. {
  52. this.Type = type;
  53. this.Data = Json.Object2Byte(data);
  54. }
  55. /// <summary>
  56. /// 将当前模型转换为 byte 数组
  57. /// </summary>
  58. /// <returns></returns>
  59. public byte[] ToByte()
  60. {
  61. List<byte> result = new List<byte>();
  62. result.AddRange(BitConverter.GetBytes(Type));
  63. if (Data != null)
  64. {
  65. result.AddRange(BitConverter.GetBytes((int)Data.Length));
  66. result.AddRange(Data);
  67. }
  68. else
  69. {
  70. result.AddRange(BitConverter.GetBytes((int)0));
  71. result.AddRange(new byte[] { });
  72. }
  73. return result.ToArray();
  74. }
  75. /// <summary>
  76. /// 转换为模型
  77. /// </summary>
  78. /// <param name="bytes"></param>
  79. /// <returns></returns>
  80. public static TcpDataModel ToModel(byte[] bytes)
  81. {
  82. TcpDataModel model = null;
  83. try
  84. {
  85. int type = BitConverter.ToInt32(bytes, 0);
  86. int length = BitConverter.ToInt32(bytes, 4);
  87. byte[] data_byte = bytes.Skip(8).Take(length).ToArray();
  88. model = new TcpDataModel(type, data_byte);
  89. }
  90. catch { }
  91. return model;
  92. }
  93. }
  94. }