上一节中我们对数据的接收进行了加工处理,是接收和发送的数据变的不是那么的零散了,这节我们来解决我们之前所说的TCP协议带来的粘包问题,方法是使用包头+数据信息的方法.试想一下哈,我们在发送数据的时候每次都要字节实现一次封装包头+消息内容的方式,那岂不是很烦,所以我们使用下面的类来进行统一的封装.使用的时候直接调用即可啦~~~
using System;
using ProtoBuf;
using UnityEngine;
/// <summary>
/// 使用Protobuf序列化类
/// </summary>
public class ProMsgHelp
{
/// <summary>
/// 编码
/// </summary>
/// <param name="msgBase"></param>
/// <returns></returns>
public static byte[] Encode(IExtensible msgBase)
{
using (var memory = new System.IO.MemoryStream())
{
Serializer.Serialize(memory, msgBase);
return memory.ToArray();
}
}
/// <summary>
/// 解码
/// </summary>
/// <param name="protoName"></param>
/// <param name="bytes"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <returns></returns>
public static IExtensible Decode(string protoName, byte[] bytes, int offset, int count)
{
using (var memory = new System.IO.MemoryStream(bytes, offset, count))
{
System.Type t = System.Type.GetType(protoName);
return (IExtensible) Serializer.NonGeneric.Deserialize(t, memory);
}
}
/// <summary>
/// 编码协议名(2字节长度 + 字符串)
/// </summary>
/// <param name="msgBase"></param>
/// <returns></returns>
public static byte[] EncodeName(IExtensible msgBase)
{
Debug.Log("ProMsgHelp==>EncodeName: " + msgBase.ToString());
//名字bytes和长度
byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(msgBase.ToString());
Int16 len = (Int16) nameBytes.Length;
Debug.Log("len::: " + len);
//申请bytes数值
byte[] bytes = new byte[2 + len];
//组装2字节的长度信息
//按照小端编码的
bytes[0] = (byte) (len % 256);
bytes[1] = (byte) (len / 256);
Debug.Log("bytes[0] " + bytes[0]);
Debug.Log("bytes[1] " + bytes[1]);
//组装名字bytes
Array.Copy(nameBytes, 0, bytes, 2, len);
return bytes;
}
/// <summary>
/// 解码协议名(2字节长度 + 字符串)
/// </summary>
/// <param name="bytes"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <returns></returns>
public static string DecodeName(byte[] bytes, int offset, out int count)
{
count = 0;
//bytes.Length必须大于2字节
if (bytes.Length < offset + 2)
{
return "";
}
//读取长度
Int16 len = (Int16) ((bytes[offset + 1] << 8) | bytes[offset]); //解决大小端编码的问题 所以才不用BitConverter.ToInt16();
//长度必须足够
if (bytes.Length < offset + 2 + len)
{
return "";
}
//解析
count = 2 + len;
string name = System.Text.Encoding.UTF8.GetString(bytes, offset + 2, len);
return name;
}
}
上面的注释应该比较清晰了,这里就不累述了…