您的位置:首页 > 理论基础 > 计算机网络

Unity——通过byte字节流进行网络传输,如何将一个类转换为一个byte字节流,再从byte字节流转换为一个类

2018-03-27 19:30 489 查看
客户端之间进行网络传输的时候, 如何将一个类转换为字节流, 再从字节流转换为一个类


在类转换为Byte字节流的时候 需要定义一个规则/协议...协议即一个规定, 在字节流的什么位置存储什么样的信息, 但要注意,除了Int short等固定长度类型, 还有String不定长度类型, 我们通常存入一个string的长度后面再存内容,这样方便反解析zi


将一个Girl的信息 转换为字节流  再转换回Girl

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text;

public class Girl
{
//基本固定属性
byte age;   //1byte
byte sex;   //1byte
float height;//4byte
int weight; //4byte
short threeD;//2btye ——》基本长度共12Byte
//长度不定属性
string name;    //Byte长度不定
//第二个不定属性
string address;

/// <summary>
/// 将Gril这个类 变成一个Byte字节流
/// </summary>
/// <returns></returns>
public byte[] GetNetBytes()
{
//基本属性字节流
byte[] result = new byte[12];
//自定义协议
result[0] = this.age;
result[1] = this.sex;
//如何将float转换为Byte数组
byte[] heightBytes = BitConverter.GetBytes(this.height);
Buffer.BlockCopy(heightBytes, 0, result, 2, 4);
byte[] weightBytes = BitConverter.GetBytes(this.weight);
Buffer.BlockCopy(weightBytes, 0, result, 6, 4);
byte[] threeDBytes = BitConverter.GetBytes(this.threeD);
Buffer.BlockCopy(threeDBytes, 0, result, 10, 2);

return result;
}

/// <summary>
/// 变长的string类型加入字节流
/// </summary>
/// <returns></returns>
public byte[] GetNetBytesNameAddr()
{
//不定长string
byte[] nameBytes = System.Text.Encoding.Default.GetBytes(this.name);
byte[] addrBytes = System.Text.Encoding.Default.GetBytes(this.address);
//字节流容量 = 定长+2+不定长长度
byte[] result = new byte[14+nameBytes.Length+addrBytes.Length];
//获取之前12长度的字节流
byte[] tmpResult = GetNetBytes();
//将之前12长度字节流存入当前字节流
Buffer.BlockCopy(tmpResult, 0, result, 0, 12);

byte nameLength = (byte)nameBytes.Length;
result[12] = nameLength;
Buffer.BlockCopy(nameBytes, 0, result, 13, nameBytes.Length);
int tmpLength = 13 + nameBytes.Length;

byte addrLength = (byte)addrBytes.Length;
result[tmpLength] = addrLength;
Buffer.BlockCopy(addrBytes, 0, result, tmpLength + 1, addrBytes.Length);
return result;
}

/// <summary>
/// 将一个字节流转换成一个Class
/// </summary>
public void GetFromNet(byte[] result)
{
this.age = result[0];
this.sex = result[1];
this.height = BitConverter.ToSingle(result, 2);
this.weight = BitConverter.ToInt32(result, 6);
this.threeD = BitConverter.ToInt16(result, 10);
this.name = Encoding.Default.GetString(result, 12, result.Length - 12);

}
/// <summary>
/// 带有string的反解析
/// </summary>
public void GetFromNtAddress(byte[]result)
{
this.age = result[0];
this.sex = result[1];
this.height = BitConverter.ToSingle(result, 2);
this.weight = BitConverter.ToInt32(result, 6);
this.threeD = BitConverter.ToInt16(result, 10);
this.name = Encoding.Default.GetString(result, 12, result.Length - 12);

//name长度
byte nameLength = result[12];
this.name = Encoding.Default.GetString(result, 13, result.Length);
//
byte addrLength = result[13 + nameLength];
this.address = Encoding.Default.GetString(result, 13 + 1 + nameLength, addrLength);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: