public void Send(string msg) { //byte[] result = Encoding.UTF8.GetBytes(msg); //Encoding.Default.GetBytes(msg) //Buffer //Arrary //BitConvert //MemoryStream //StreamReader //StreamWriter //BinaryReader //BinaryWriter //数据信息 NetModel model = new NetModel() { ID = 1, Commit = "LanOu", Message = msg }; byte[] dataModel = NetModel.Serialize(model); //长度信息 int len = dataModel.Length; byte[] dataLength = BitConverter.GetBytes(len); //合并数组 byte[] result = NetEncode.Encode(dataModel); tc.GetStream().Write(result, 0, result.Length); }
private void ReadData() { byte[] data = NetEncode.Decode(ref receiveCache); if (null != data) { NetModel item = NetModel.Deserialize(data); print("cleint:" + item.Message); ReadData(); } else { isReceiving = false; } }
public static NetModel Deserialize(byte[] msg) { try { using (MemoryStream ms = new MemoryStream()) { ms.Write(msg, 0, msg.Length); ms.Position = 0; NetModel result = Serializer.Deserialize <NetModel>(ms); return(result); } } catch (Exception e) { print(e.Message); return(null); } }
public static byte[] Serialize(NetModel model) { try { using (MemoryStream ms = new MemoryStream()) { Serializer.Serialize <NetModel>(ms, model); byte[] result = new byte[ms.Length]; ms.Position = 0; ms.Read(result, 0, result.Length); return(result); } } catch (Exception e) { print(e.Message); return(null); } }