TcpDataModel.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. /// 将当前模型转换为 byte 数组
  25. /// </summary>
  26. /// <returns></returns>
  27. public byte[] ToByte()
  28. {
  29. List<byte> result = new List<byte>();
  30. result.AddRange(BitConverter.GetBytes(Type));
  31. if (Data != null)
  32. {
  33. result.AddRange(BitConverter.GetBytes((int)Data.Length));
  34. result.AddRange(Data);
  35. }
  36. else
  37. {
  38. result.AddRange(BitConverter.GetBytes((int)0));
  39. result.AddRange(new byte[] { });
  40. }
  41. return result.ToArray();
  42. }
  43. /// <summary>
  44. /// 转换为模型
  45. /// </summary>
  46. /// <param name="bytes"></param>
  47. /// <returns></returns>
  48. public static TcpDataModel ToModel(byte[] bytes)
  49. {
  50. TcpDataModel model = null;
  51. try
  52. {
  53. int type = BitConverter.ToInt32(bytes, 0);
  54. int length = BitConverter.ToInt32(bytes, 4);
  55. byte[] data_byte = bytes.Skip(8).Take(length).ToArray();
  56. model = new TcpDataModel();
  57. model.Type = type;
  58. model.Data = data_byte;
  59. }
  60. catch { }
  61. return model;
  62. }
  63. }
  64. }