标签:
Protobuf 是google发起的一种二进制格式,目前广泛应用在各种开发语言中。详情请看:https://code.google.com/p/protobuf/点击打开链接,关于C#的Protobuf实现,目前公认比较好的就是Protobuf-net。
因为GOOGLE自带支持的语言不包括C#,所以当使用了开元项目Protobuf-net解析google protobuf 格式的通信数据时,需要使用第三方开源库Protobuf-net。 下载地址:点击打开链接 https://github.com/mgravell/protobuf-net
1. 下载后可能会有很多文件,只需要复制protobuf-net到工程中即可。
2.下载后建立一个文件smcs.rsp,内容是-unsafe,前后都不能有空格,放到Assets目录下即可。
3.把工程设置为.Net 2.0 subset,因为.Net 2.0是无法在ios上用这个方法的
4.重启unity。
也可直接导入unitypackage,下载地址:点击打开链接。(上面的1,2,3,4都不需要了)。
下面简单介绍下序列化过程:
//生成数据
MainPacket tempPacket = new MainPacket(){ header = HEADER,timestamp = timestamp,cmdCode = cmdCode,contentLength = contentLength,content = contentStr,tail = TAIL};
byte[] buffer = null;
using ( MemoryStream ms = new MemoryStream ( ) )
{
//将数据序列化
Serializer.Serialize ( ms , tempPacket );
ms.Position = 0;
int length = (int)ms.Length;
buffer = new byte[length];
ms.Read(buffer, 0 ,length);
//发送请求
try
{
connectPanle.SetActive(true);
socket.Send(buffer);
}
catch
{
connectPanle.SetActive(false);
Debug.Log("socket error");
}
}
//读取消息长度
readCount = socket.EndReceive(ar);//调用这个函数来结束本次接收并返回接收到的数据长度。
Debug.Log("读取消息长度" + readCount);
byte[] bytes = new byte[readCount];//创建长度对等的bytearray用于接收
Buffer.BlockCopy(readM, 0, bytes, 0, readCount);//拷贝读取的消息到 消息接收数组
//反序列化1
MainPacket s = new MainPacket();
MemoryStream ms = new MemoryStream();
ms.Write(bytes,0,readCount);
s = ProtoBuf.Serializer.Deserialize<MainPacket>(ms);
Debug.Log("错误代码:"+s.cmdCode);
// 对包头和包尾进行解析
if(s.header != HEADER && s.tail != TAIL)
{
Debug.Log("非法包");
return;
}
else
{
Debug.Log("执行成功");
messages.Add(s);
}
//反序列化2
// MainPacket newData = null;
// using ( MemoryStream ms = new MemoryStream ( bytes ) )
// {
// newData = ProtoBuf.Serializer.Deserialize<MainPacket>(ms);
// }
// Debug.Log ( "newData.cmdCode=" + newData.cmdCode );标签:
原文地址:http://blog.csdn.net/u012976984/article/details/44992553