The socket of unity explorer transmits protobuf byte streams (1) and unityprotobuf

Source: Internet
Author: User

The socket of unity explorer transmits protobuf byte streams (1) and unityprotobuf

Recently, I am working on a card and board game project. I need to use socket to transmit protobuf byte streams. After searching for some blogs and articles on the internet, I found that it is not comprehensive, so I will share all the source code I have studied with you, because at the beginning, there may be some shortcomings. Thank you for making a brick ~~

This article mainly refers to the serialization and parsing of protocol buffer files. I will not talk much about it, but I will do it directly.

1 /// <summary> 2 /// method 3 for serializing the message to binary. /// </summary> 4 /// <param name = "model"> to serialize object </param> 5 public static byte [] Serialize (IExtensible model) 6 {7 try 8 {9 // create Stream object 10 MemoryStream MS = new MemoryStream () 11 // use ProtoBuf's built-in serialization tool to serialize IExtensible object 12 Serializer. serialize <IExtensible> (ms, model); 13 // create a list-level array to save the serialized stream 14 byte [] bytes = new byte [ms. length]; 15 // set the stream position to 016 ms. position = 0; 17 // read the content in the stream to the binary array for 18 ms. read (bytes, 0, bytes. length); 19 return bytes; 20} 21 catch (Exception e) 22 {23 Debug. log ("serialization failed:" + e. toString (); 24 return null; 25} 26}

Each message in the protobuf file can be converted into a class in c # by using the ProtoGen tool provided by protocol buffer, for example

message Test {    required string test1= 1;    required string test2= 2;}

After conversion, it becomes

 1   [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"SedReq")] 2   public partial class Test : global::ProtoBuf.IExtensible 3   { 4     public Test() {} 5      6     private string _test1; 7     [global::ProtoBuf.ProtoMember(1, IsRequired = true, Name=@"test1", DataFormat = global::ProtoBuf.DataFormat.Default)] 8     public string test1 9     {10       get { return _test1; }11       set { _test1 = value; }12     }    13     private string _test2;14     [global::ProtoBuf.ProtoMember(2, IsRequired = true, Name=@"test2", DataFormat = global::ProtoBuf.DataFormat.Default)]15     public string test216     {17       get { return _test2; }18       set { _test2 = value; }19     }20     private global::ProtoBuf.IExtension extensionObject;21     global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)22       { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); }23   }

Regardless of all the code with global, you will find that the converted c # class is exactly the same as a standard c # entity class, and these converted classes are inherited to ProtoBuf. IExtensible, so the parameter type of the serialization function above is IExtensible

With serialization, deserialization is also required, that is, byte [] deserialization is a type object inherited to IExtensible.

1 /// <summary> 2 // deserialize the received message into an IExtensible object 3 /// </summary> 4 /// <param name = "msg"> the byte stream of the received message. </param> 5 // <returns> </returns> 6 public static T DeSerialize <T> (byte [] bytes) where T: IExtensible 7 {8 try 9 {10 MemoryStream ms = new MemoryStream () 11 // write messages to the stream for 12 ms. write (bytes, 0, bytes. length); 13 // set the stream position to 014 ms. position = 0; 15 // deserialization object 16 T result = Serializer. deserialize <T> (MS); 17 return result; 18} 19 catch (Exception e) 20 {21 Debug. log ("deserialization failed:" + e. toString (); 22 return null; 23} 24}

Because the deserialized object inherits from the IExtensible class, the returned value must be defined using generic constraints to ensure the versatility of functions.

The tool is ready, and the next step is to test the code.

1     public void Test()2     {3         Test test = new Test() { test1 = "123", test2 = "456" };4         byte[] bytes = Serialize(test);5         Test test2 = DeSerialize<Test>(bytes);6         Debug.Log(test2.test1 + test2.test2);7     }

Output 123456

Attachment protobuf-net.dll document

Http://files.cnblogs.com/files/unityExplorer/protobuf-net.zip

Pre-compilation and conversion tools

Http://files.cnblogs.com/files/unityExplorer/protoGen.zip

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.