原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2019/0119/344.html
常州微信小程序开发-Unity3D使用Protobuf、ProtobufHelper
在序列化,Protobuf有着天然的优势,Protobuf作为Google的一个开源序列化库,因为使用的数据压缩算法等优化,序列化的数据较Xml更小,速度更快。下面常州网站开发培训就给大家介绍下Protobuf和ProtobufHelper的使用。
using System.Text;
using System.IO;
using ProtoBuf;
namespace Protobuf
{
class ProtobufHelper
{
/// <summary>
/// 序列化成string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns>返回字符串</returns>
public static string Serialize<T>(T t)
{
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize<T>(ms, t);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// 序列化到文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <param name="data"></param>
public static void Serialize<T>(string path, T data)
{
using (Stream file = File.Create(path))
{
Serializer.Serialize<T>(file, data);
file.Close();
}
}
/// <summary>
/// 常州企业培训根据字符串反序列化成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="content"></param>
/// <returns></returns>
public static T DeSerialize<T>(string content)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
T t = Serializer.Deserialize<T>(ms);
return t;
}
}
/// <summary>
/// 根据文件流返回对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="filestream"></param>
/// <returns></returns>
public static T DeSerialize<T>(Stream filestream)
{
return Serializer.Deserialize<T>(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
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// 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<string> _Parent = new global::System.Collections.Generic.List<string>();
[global::ProtoBuf.ProtoMember(2, Name=@"Parent", DataFormat = global::ProtoBuf.DataFormat.Default)]
public global::System.Collections.Generic.List<string> 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<Person> persons = new List<Person>() { p1, p2 };
//序列化存储
Protobuf.ProtobufHelper.Serialize<List<Person>>(Path, persons);
//或者
//string content = Protobuf.ProtobufHelper.Serialize<List<Person>>(persons);
//File.WriteAllText(Path, content);
//将数据从文件中读取出来,反序列化
List<Person> Persons1;
using (Stream file = File.OpenRead(Path))
{
Persons1 = Protobuf.ProtobufHelper.DeSerialize<List<Person>>(file);
}
//或者
//List<Person> Persons1 = Protobuf.ProtobufHelper.DeSerialize<List<Person>>(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<MessageReceivedEventArgs>(websocket_MessageReceived);
websocket.Open();
}
/// <summary>
/// 连接上常州微信公众平台服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void websocket_Opened(object sender, EventArgs e)
{
websocket.Send(PlayName + "Has Join The Game");
}
/// <summary>
/// 接受连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
//TODO:这里要做消息分发处理,我这里就暂时默认服务器下发的就是Person的Protobuf的消息
var personMsg = ProtobufHelper.DeSerialize<Person>(e.Message);
ServerMessage += "Name:" + personMsg.Name + " Gender:" + personMsg.Gender + " Info:" + personMsg.Msg + "\n";
}
/// <summary>
/// 断开连接常州网站开发建设
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void websocket_Closed(object sender, EventArgs e)
{
websocket.Close();
}
}
上篇:上一篇:常州小程序开发-u3D TriggerEnter和CollisionEnter的差别
下篇:下一篇:常州手游开发-U3D连接Mysql对数据库