联网游戏的信息传输都是以字节流(字节数组)形式传输数据,本文展示基本数据类型与字节流互相转换 girl模型有四个信息,GetByteNets方法将信息转化为字节流,GetGirlFormNets()方法展示如何将字节流转化为信息 public byte[] GetByteNets() //将这个对象转化为字节流 byte[] result= new byte[11]; byte[] heightBytes = BitConverter.GetBytes(this.height); //字节流拷贝(源字节流,从第0个开始拷贝,目标字节流,拷贝到目标字节流第offset个,拷贝长度为原字节流长度) Buffer.BlockCopy(heightBytes,0,result,offset,heightBytes.Length); offset += heightBytes.Length; byte[] weightBytes = BitConverter.GetBytes(this.weight); Buffer.BlockCopy(weightBytes, 0, result, offset, weightBytes.Length); offset += weightBytes.Length; byte[] ageBytes = BitConverter.GetBytes(this.age); Buffer.BlockCopy(ageBytes, 0, result, offset, ageBytes.Length); offset += ageBytes.Length; public Girl GetGirlFromNet(byte[] buffer) //输入字节流 输出对象 Girl result = new Girl(); result.height = BitConverter.ToInt16(buffer, 1); result.weight = BitConverter.ToSingle(buffer, 3); result.age = BitConverter.ToInt32(buffer, 7);
|