聯(lián)網(wǎng)游戲的信息傳輸都是以字節(jié)流(字節(jié)數(shù)組)形式傳輸數(shù)據(jù),本文展示基本數(shù)據(jù)類型與字節(jié)流互相轉(zhuǎn)換 girl模型有四個信息,GetByteNets方法將信息轉(zhuǎn)化為字節(jié)流,GetGirlFormNets()方法展示如何將字節(jié)流轉(zhuǎn)化為信息 public byte[] GetByteNets() //將這個對象轉(zhuǎn)化為字節(jié)流 byte[] result= new byte[11]; //將身高參數(shù)轉(zhuǎn)化為字節(jié)流(short轉(zhuǎn)字節(jié)流) byte[] heightBytes = BitConverter.GetBytes(this.height); //字節(jié)流拷貝(源字節(jié)流,從第0個開始拷貝,目標字節(jié)流,拷貝到目標字節(jié)流第offset個,拷貝長度為原字節(jié)流長度) Buffer.BlockCopy(heightBytes,0,result,offset,heightBytes.Length); offset += heightBytes.Length; //將體重參數(shù)轉(zhuǎn)化為字節(jié)流 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) //輸入字節(jié)流 輸出對象 Girl result = new Girl(); result.height = BitConverter.ToInt16(buffer, 1); result.weight = BitConverter.ToSingle(buffer, 3); result.age = BitConverter.ToInt32(buffer, 7);
|