using Azylee.Core.DataUtils.SerializeUtils; using Azylee.Core.WindowsUtils.ConsoleUtils; using Azylee.Jsons; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Azylee.YeahWeb.SocketUtils.TcpUtils { /// /// Tcp 传输数据模型 /// public class TcpDataModel { /// /// 类型 /// public int Type { get; set; } /// /// 数据 /// public byte[] Data { get; set; } /// /// 默认构造函数 /// public TcpDataModel() { } /// /// 构造函数(仅指令) /// /// public TcpDataModel(int type) { this.Type = type; } /// /// 构造函数(默认) /// /// /// public TcpDataModel(int type, byte[] data) { this.Type = type; this.Data = data; } /// /// 构造函数(自动转换) /// /// /// public TcpDataModel(int type, object data) { this.Type = type; this.Data = Json.Object2Byte(data); } /// /// 将当前模型转换为 byte 数组 /// /// public byte[] ToByte() { List result = new List(); result.AddRange(BitConverter.GetBytes(Type)); if (Data != null) { result.AddRange(BitConverter.GetBytes((int)Data.Length)); result.AddRange(Data); } else { result.AddRange(BitConverter.GetBytes((int)0)); result.AddRange(new byte[] { }); } return result.ToArray(); } /// /// 转换为模型 /// /// /// public static TcpDataModel ToModel(byte[] bytes) { TcpDataModel model = null; try { int type = BitConverter.ToInt32(bytes, 0); int length = BitConverter.ToInt32(bytes, 4); byte[] data_byte = bytes.Skip(8).Take(length).ToArray(); model = new TcpDataModel(type, data_byte); } catch { } return model; } } }