常州微信小程序开发-Unity3D使用Protobuf、ProtobufHelper
在序列化,Protobuf有着天然的优势,Protobuf作为Google的一个开源序列化库,因为使用的数据压缩算法等优化,序列化的数据较Xml更小,速度更快。下面常州网站开发培训就给大家介绍下Protobuf和ProtobufHelper的使用。
using
System.Text;
using
System.IO;
using
ProtoBuf;
namespace
Protobuf
{
class
ProtobufHelper
{
///
///序列化成string
///
///
///
/// 返回字符串
public static string
Serialize(T t)
{
using (MemoryStream ms =
new MemoryStream())
{
Serializer.Serialize(ms,
t);
return
Encoding.UTF8.GetString(ms.ToArray());
}
}
///
///序列化到文件
///
///
///
///
public static void
Serialize(string path, T data)
{
using (Stream file =
File.Create(path))
{
Serializer.Serialize(file,
data);
file.Close();
}
}
///
///
常州企业培训根据字符串反序列化成对象
///
///
///
///
public static T
DeSerialize(string content)
{
using (MemoryStream ms =
new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
T t =
Serializer.Deserialize(ms);
return t;
}
}
///
///根据文件流返回对象
///
///
///
///
public static T
DeSerialize(Stream filestream)
{
return
Serializer.Deserialize(filestream);
}
}
}
using
UnityEngine;
using
System.Collections;
using
ProtoBuf;
#if false
[ProtoContract]
public class
Person
{
[ProtoMember(1)]
public string
Name{get;
set;}
[ProtoMember(2)]
public bool
Gender{get;
set;}
[ProtoMember(3)]
public string
Msg{get;
set;}
}
#endif
//------------------------------------------------------------------------------
//
// This code was generated
by a tool.
//
// Changes to this file may
cause incorrect behavior and will be lost if
// the code is
regenerated.
//
//------------------------------------------------------------------------------
// Generated from:
PersonInfo.proto
namespace
PersonInfo
{
[global::System.Serializable,
global::ProtoBuf.ProtoContract(Name=@"Person")]
public
partial class Person : global::ProtoBuf.IExtensible
{
public
Person(){}
private string _Child =
"";
[global::ProtoBuf.ProtoMember(1,
IsRequired = false, Name=@"Child", DataFormat =
global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string
Child
{
get{return
_Child;}
set{_Child =
value;}
}
private readonly
global::System.Collections.Generic.List _Parent = new
global::System.Collections.Generic.List();
[global::ProtoBuf.ProtoMember(2,
Name=@"Parent", DataFormat =
global::ProtoBuf.DataFormat.Default)]
public
global::System.Collections.Generic.List Parent
{
get{return
_Parent;}
}
private string
_Name;
[global::ProtoBuf.ProtoMember(3,
IsRequired = true, Name=@"Name", DataFormat =
global::ProtoBuf.DataFormat.Default)]
public string
Name
{
get{return
_Name;}
set{_Name =
value;}
}
private bool
_Gender;
[global::ProtoBuf.ProtoMember(4,
IsRequired = true, Name=@"Gender", DataFormat =
global::ProtoBuf.DataFormat.Default)]
public bool
Gender
{
get{return
_Gender;}
set{_Gender =
value;}
}
private string
_Msg;
[global::ProtoBuf.ProtoMember(5,
IsRequired = true, Name=@"Msg", DataFormat =
global::ProtoBuf.DataFormat.Default)]
public string
Msg
{
get{return
_Msg;}
set{_Msg =
value;}
}
private
global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension
global::ProtoBuf.IExtensible.GetExtensionObject(bool
createIfMissing)
{return
global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject,
createIfMissing);}
}
[global::System.Serializable,
global::ProtoBuf.ProtoContract(Name=@"SearchRequest")]
public
partial class SearchRequest :
global::ProtoBuf.IExtensible
{
public
SearchRequest(){}
private string
_query;
[global::ProtoBuf.ProtoMember(1,
IsRequired = true, Name=@"query", DataFormat =
global::ProtoBuf.DataFormat.Default)]
public string
query
{
get{return
_query;}
set{_query =
value;}
}
private int _page_number
= default(int);
[global::ProtoBuf.ProtoMember(2,
IsRequired = false, Name=@"page_number", DataFormat =
global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int
page_number
{
get{return
_page_number;}
set{_page_number =
value;}
}
private int
_result_per_page = (int)10;
[global::ProtoBuf.ProtoMember(3,
IsRequired = false, Name=@"result_per_page", DataFormat =
global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue((int)10)]
public int
result_per_page
{
get{return
_result_per_page;}
set{_result_per_page =
value;}
}
private
SearchRequest.Corpus _corpus =
SearchRequest.Corpus.UNIVERSAL;
[global::ProtoBuf.ProtoMember(4,
IsRequired = false, Name=@"corpus", DataFormat =
global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(SearchRequest.Corpus.UNIVERSAL)]
public
SearchRequest.Corpus corpus
{
get{return
_corpus;}
set{_corpus =
value;}
}
[global::ProtoBuf.ProtoContract(Name=@"Corpus")]
public enum
Corpus
{
[global::ProtoBuf.ProtoEnum(Name=@"UNIVERSAL",
Value=0)]
UNIVERSAL =
0,
[global::ProtoBuf.ProtoEnum(Name=@"WEB",
Value=1)]
WEB = 1,
[global::ProtoBuf.ProtoEnum(Name=@"IMAGES",
Value=2)]
IMAGES = 2,
[global::ProtoBuf.ProtoEnum(Name=@"LOCAL",
Value=3)]
LOCAL = 3,
[global::ProtoBuf.ProtoEnum(Name=@"NEWS",
Value=4)]
NEWS = 4,
[global::ProtoBuf.ProtoEnum(Name=@"PRODUCTS",
Value=5)]
PRODUCTS = 5,
[global::ProtoBuf.ProtoEnum(Name=@"VIDEO",
Value=6)]
VIDEO = 6
}
private
global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension
global::ProtoBuf.IExtensible.GetExtensionObject(bool
createIfMissing)
{return
global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject,
createIfMissing);}
}
}
using
UnityEngine;
using
System.Collections;
using
ProtoBuf;
using
System;
using
System.Collections.Generic;
using
System.IO;
using
PersonInfo;
public class
ProtobufTest1 : MonoBehaviour
{
private const string
Path = "C://data";
void Start()
{
Person p1 = new
Person(){Name = "小明", Gender =
true};
Person p2 = new
Person(){Name = "小红", Gender =
false};
List
persons = new List(){p1,
p2};
//序列化存储
Protobuf.ProtobufHelper.Serialize>(Path,
persons);
//或者
//string content =
Protobuf.ProtobufHelper.Serialize>(persons);
//File.WriteAllText(Path,
content);
//将数据从文件中读取出来,反序列化
List
Persons1;
using
(Stream file = File.OpenRead(Path))
{
Persons1 =
Protobuf.ProtobufHelper.DeSerialize>(file);
}
//或者
//List Persons1 =
Protobuf.ProtobufHelper.DeSerialize>(content);
foreach (Person p in
Persons1)
{
Debug.Log("Name:" +
p.Name + ": " + "Gender:" +
p.Gender);
}
}
}
using
Protobuf;
using
System;
using
UnityEngine;
using
WebSocket4Net;
using
PersonInfo;
public class
ProtobufTest2 : MonoBehaviour
{
//服务器IP地址和端口号
private string
ServerAdress;
//
常州软件技术培训玩家名字
private string PlayName
= "Aladdin";
//发送的消息
private string
message;
//接收到服务器发回来的消息
private string
ServerMessage;
public WebSocket
websocket;
void Start()
{
//服务器IP地址和端口号
ServerAdress =
"ws://127.0.0.1:2014/";
message = "Clients Send
Message";
ServerMessage = "Server
Message";
Application.runInBackground
= true;
}
void OnGUI()
{
//绘制2个TxtBox文本输入框
PlayName =
GUI.TextField(new Rect(10, 10, 100, 20), PlayName);
message =
GUI.TextArea(new Rect(10, 40, 200, 200), message);
ServerMessage =
GUI.TextArea(new Rect(10, 250, 400, 200),
ServerMessage);
//连接到常州平台运营服务器
if
(GUI.Button(new Rect(250, 10, 150, 40), "Client连接"))
{
ConnectToServer();
};
if
(websocket != null)
{
//测试向服务器发送消息
if (GUI.Button(new
Rect(250, 60, 150, 40), "SendMessageToServer"))
{
if (message.Length <
1 || PlayName.Length < 1)
return;
websocket.Send(ProtobufHelper.Serialize(new
Person(){Name = this.PlayName,
Gender = true, Msg = message}));
};
//断开连接按钮
if (GUI.Button(new
Rect(250, 120, 150, 40), "CloseSocket"))
{
websocket.Close();
websocket =
null;
};
}
}
private void
ConnectToServer()
{
websocket = new
WebSocket(ServerAdress);
websocket.Opened += new
EventHandler(websocket_Opened);
websocket.Closed += new
EventHandler(websocket_Closed);
websocket.MessageReceived
+= new EventHandler(websocket_MessageReceived);
websocket.Open();
}
///
///连接上常州微信公众平台服务器
///
///
///
private void
websocket_Opened(object sender, EventArgs e)
{
websocket.Send(PlayName
+ "Has Join The Game");
}
///
///接受连接
///
///
///
private void
websocket_MessageReceived(object sender, MessageReceivedEventArgse)
{
//TODO:这里要做消息分发处理,我这里就暂时默认服务器下发的就是Person的Protobuf的消息
var
personMsg = ProtobufHelper.DeSerialize(e.Message);
ServerMessage += "Name:"
+ personMsg.Name + "Gender:"
+ personMsg.Gender + "Info:"
+ personMsg.Msg + "\n";
}
///
///断开连接常州网站开发建设
///
///
///
private void
websocket_Closed(object sender, EventArgs e)
{
websocket.Close();
}
}
">