//发送消息 public void write(byte type, int area, int command, object msg) { ByteArray ba = new ByteArray(); ba.write(type); ba.write(area); ba.write(command); if (msg != null) { ba.write(SeriaLiseUtil.Encode(msg)); } //长度编码 ByteArray data = new ByteArray(); data.write(ba.Length); data.write(ba.GetBuffer()); //发送 try { socket.Send(data.GetBuffer()); } catch (Exception e) { Debug.Log("网络错误:" + e.Message); } }
//消息体解码 private SocketModel MDecode(byte[] data) { ByteArray ba = new ByteArray(data); SocketModel model = new SocketModel(); byte type; int area; int command; ba.read(out type); ba.read(out area); ba.read(out command); model.type = type; model.area = area; model.command = command; if (ba.Readable) { byte[] msg; ba.read(out msg, ba.Length - ba.Position); //反序列化 model.msg = SeriaLiseUtil.Decode(msg); ba.Close(); } return(model); }