看到前面的代码不知道大家有没有发现一个问题哈,尽管我们使用前面的代码也可以发送数据,但是我们发送的都是字符串,而且是写死的那种,真正的网络协议不用想肯定不是这样的啦!那么本节我们就开始简述一下我们在发送数据的时候应该使用怎样的数据类型来正确的在网络上面收发和交换数据呢?
这个问题的答案很简单,我们使用Protobuf来解决这样的一个问题哈!
至于Protobuf是什么呢?大家可以阅读这篇博文去了解一下:
Protobuf介绍
在unity中使用Protobuf我们需要引入"protobuf-net"这个程序集即可,然后使用Goole提供好的编译工具将我们写好的Protobuf文件转成我们工程里面需要的.cs文件即可.
下面展示一个简单的Proto文件
message MsgMove_Pro{
optional int32 x = 1;
optional int32 y = 2;
optional int32 z = 3;
}
message MsgAttack_Pro{
optional string desc = 1;
}
下面是对应的使用工具转成的cs文件
//------------------------------------------------------------------------------
// <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: proto/BattleMsg_Pro.proto
[global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"MsgMove_Pro")]
public partial class MsgMove_Pro : global::ProtoBuf.IExtensible
{
public MsgMove_Pro() {}
private int _x = default(int);
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"x", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int x
{
get { return _x; }
set { _x = value; }
}
private int _y = default(int);
[global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"y", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int y
{
get { return _y; }
set { _y = value; }
}
private int _z = default(int);
[global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"z", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)]
[global::System.ComponentModel.DefaultValue(default(int))]
public int z
{
get { return _z; }
set { _z = 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=@"MsgAttack_Pro")]
public partial class MsgAttack_Pro : global::ProtoBuf.IExtensible
{
public MsgAttack_Pro() {}
private string _desc = "";
[global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"desc", DataFormat = global::ProtoBuf.DataFormat.Default)]
[global::System.ComponentModel.DefaultValue("")]
public string desc
{
get { return _desc; }
set { _desc = value; }
}
private global::ProtoBuf.IExtension extensionObject;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{ return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }
}