Unity3d client and Java server end use Protobuf__java

Source: Internet
Author: User
Tags serialization svn

Category: Unity3d game development Java Basics

A few days ago, a netizen asked me about Unity3d inside the use of Protobuf method, something dragged until now to write this article, sorry ha.

This article tests the environment:

System: WINDOWS 7 (3rd, 6), OS X 10.9 (step 4th)

Software: VS 2012 (3rd, 6 steps), Eclipse (5th, 6 steps)

Hardware: IPad 2 (4th step), Macbook Pro Mid 2012 (step 4th)


Article directory:

1, about the protobuf of C # implementation

2, why some protobuf released to iOS can not be used, or even some in the PC can not be used.

3, manual processing of C # version of the PROTOBUF

3.1. Create a C # project, manually create each data model class that you want to serialize or deserialize by PROTOBUF, and then export the DLL

3.2. Create a C # project for serialization, and then run the build DLL

3.3, the above two projects generated by the DLL dragged to unity

4, in unity in the deserialization of PROTOBUF

5, the service side Java also uses PROTOBUF

6, too annoying. The client also wants to automatically process the PROTOBUF


1, about the protobuf of C # implementation

First, u3d inside Protobuf is using C # implementation, so there are several optional C # implementations:

C #: Http://code.google.com/p/protobuf-csharp-port
C #: http://code.google.com/p/protosharp/
C #: https://silentorbit.com/protobuf/
c#/.net/wcf/vb:http://code.google.com/p/protobuf-net/


I choose http://code.google.com/p/protobuf-net/here (You can https://code.google.com/p/protobuf-net/downloads/list Here to download to his code and tools), it is better to provide a variety of platform support, after decompression in the "full" directory can see the support of each platform. (now Google is a variety of blocked, if you do not open the above address, you can download my upload to Csdn, the inside of the CSharp folder is the platform of the PROTOBUF required DLL, click to download protobuf-net).


See the unity inside, it's protobuf-net.dll will be we are ready to use.


2, why some protobuf released to iOS can not be used, or even some in the PC can not be used.

A, Protobuf uses JIT, which is dynamically compiled at run time, and this feature is not supported when Unity is released to iOS. As a result, you'll be able to run it on your PC, and you'll have problems posting to iOS.

B, Protobuf is written based on the. NET 2.0 framework, and unity only supports. NET 2.0, or some of the more features in 2.0, and you publish a subset of. NET 2.0 in Unity. The latter you only need to modify the settings on the player setting.

The above two can also apply to other Third-party libraries, if you download a PC or C # inside the normal use of the class library, in the u3d can not be used, then please check whether it is the above two causes.


3, manual processing of C # version of the Protobuf

Knowing the above problem, we just choose a. net2.0 protobuf, then it is not JIT, it can be used normally.

The idea here is:

3.1. Create a C # project, manually create each data model class that you want to serialize or deserialize by PROTOBUF, and then export the DLL

Take vs as an example, first, create a class library project: "Files" > "new" > "Project" > "Class Library" (Remember to select. NET Framework 2.0)


Add Unity's Protobuf DLL to the project reference


Then suppose you have a class workerinfo that needs to be serialized and deserialized by Protobuf, then create a Workerinfo class that reads as follows:[CSharp] View plain copy using system;   using system.collections.generic;   using  system.text;   using protobuf;   namespace com.yourcompany.project.proto.module{        [ProtoContract]       public class  workerinfo {                  [ Protomember (1)]           public int workerId;                  [protomember (2)]            public int leftClosingTimeSec;                 [protomember (3)]            public int buildingId;             }  }   Press SHIFT+F6 to generate the DLL, in the project Bin\Debug directory can find ProtoModelDLL.dll


3.2. Create a C # project for serialization, and then run the build DLL
Also take vs as an example, first create a console application: "Files" > "new" > "Project" > "Console Application" (Remember to select the. NET Framework 2.0)


Adding Protobuf and 3.1-generated DLLs to references


Written in a project-generated Program.cs:[CSharp] View plain copy using system;   using system.collections.generic;   using  system.text;   using protobuf.meta;   using protobuf;   using  protobuf.compiler;   using com.yourcompany.project.proto.module;          namespace protomodelserializercreator   {       class  program       {           static  void main (String[] args)            {                var model =  Typemodel.create ();                   model. Add (typeof (Object),  true);              & NBsp;model. Add (typeof (Workerinfo),  true);                   model. allowparseabletypes = true;                model. autoaddmissingtypes = true;                model. Compile ("Protomodelserializer",  "ProtoModelSerializer.dll");            }       }  }  
Then Ctrl+f5 run, and you can see ProtoModelSerializer.dll in the bin\debug.

3.3, the above two projects generated by the DLL (ProtoModelDLL.dll and ProtoModelSerializer.dll) and Protobuf-net.dll dragged to unity

how to use. Look at the 4th step.

4, in unity in the deserialization of PROTOBUF

Because the general game client requests the amount of data is relatively simple, but also relatively few, so our front-end request is not directly binary request. And the front end receives the back end to use the PROTOBUF, therefore. This only discusses Protobuf deserialization.

The code is simple, write a test code below:[CSharp] View plain copy using unityengine;   using system.collections;   using  protobuf.meta;   using com.yourcompany.project.proto.module;   using System.IO;    using com.duoyu001.proto.building;   using com.duoyu001.proto.worker;       public class testproto : monobehaviour   {           // init       void Start  ()         {           byte[]  datafromserv = new byte[]{8, 233, 7, 16, 100, 24, 1};     //these bytes are generated by server                       RuntimeTypeModel  serializer = protomodelserializer.create  ();            system.io.memorystream memstream = new system.io.memorystream  ();            WorkerInfo w = new WorkerInfo  ();            serializer. deserialize  (memstream, w, w.gettype  ());    //asign value  to proto model                       Debug.Log  (w.workerid +  ", "  + w.buildingid  +  ", "  + w.leftclosingtimesec);       }  }   

After running the Unity console output information about the worker. The contents of the Datafromserv byte array in the code should actually be returned at the back end of the communication. Testing here does not involve the knowledge of socket communication.

5, the service side Java also uses PROTOBUF

See a client with protobuf so troublesome, then what will be the back end. In fact, the back end is relatively simple, with Google's official support.

Download: https://code.google.com/p/protobuf/downloads/list

After the decompression is like this (2.5.0):


Into the "Protobuf-2.5.0\java" folder, which is a MAVEN project that you directly use Maven clean Install will generate a Protobuf-java-2.5.0.jar jar package at the target directory, no maven download it here, I use MAVEN generated http://download.csdn.net/detail/ kakashi8841/6723689. This is the time to import your Java project. It's OK.

Then you write a proto file, call the "PROTOBUF-2.5.0\SRC" inside the protoc.exe to generate, it will help you generate a Java file. (see https://developers.google.com/protocol-buffers/docs/javatutorial in detail), I have here to provide a bat, used to invoke Protoc to generate Java files, It's too much trouble to enter it manually. Save it to. bat under Windows and double-click to run it.[VB] View plain copy @echo  off   echo ** setting runtime variable       rem _protosrc  is the location of your proto file directory    set _protosrc=f:\project_proto_src\trunk\ xgame-controllers\protos      rem protoexe  is the location of the Protoc.exe program that is used to generate Java from Proto     set protoexe=c:\users\john\desktop\protobuf-2.5.0\src\protoc.exe      REM  java_out_file  the location of the generated Java file directory    set java_out_file=f:\project_proto_src\trunk\ xgame-controllers\src\main\java\      for /r  "%_protosrc%"  %%i in  ( *)  do  (        set filename=%%~nxi         if  "%%~xi"   ==  "Proto"   (            %protoExe% --proto_path=%_protoSrc% --java_out=%java_out_file% %%i        )   )   
OK, so you just copy the generated Java to or directly into your Java project source directory, and then you can use it. Like what:
Take the Workerinfo as a case in front of me[Java]View plain copy package com.duoyu001.xgame;      Import Java.util.Arrays;      Import Com.duoyu001.xgame.worker.proto.WorkerInfoBuilder.WorkerInfo; public class Testproto {public static void main (string[] args) {Workerinfo w = workerinfo.newbuilder (           ). Setbuildingid (1). Setleftclosingtimesec. Setworkerid (1001). build ();           byte[] ByteArray = W.tobytearray ();       System.out.println (arrays.tostring (ByteArray)); }   }
The console will output:

Careful students will find the bytes here and the above "8, 233, 7, 16, 100, 24, 1" a bit different. The second number is-23 and 233, respectively.

In fact, this is only a byte of the symbol of the difference is not only.

Their binary representations are: 11101001


6, too annoying. The client also wants to automatically process the PROTOBUF

We see that the client does not add a class, all need to add code in two vs projects, the latter is directly based on the proto file generated code. In this way, it seems a bit unfair, and the front and back end may still write a different structure. In fact, with Protobuf I personally feel the greatest advantage:

A, small amount of data

b, generate code through the proto template, reduce the front and back end of the joint

But now only the back end is reduced and the front end is not reduced, so the second benefit is not obvious.

All right. I was not so satisfied. Therefore, I decided that the front-end should also be based on Proto to generate CS files.

So I used Java to write a tool to parse the proto file, generate a CS file based on Proto, and then use BAT to invoke the VS command line to execute the VS project build, and finally build two DLLs.

I have integrated the above commands into a bat, so the task of this bat is:

Execute Java program to generate CS file for Proto file.

Call the VS interface to build two VS projects and generate two DLLs.

Submit these two DLLs to the client's backbone via SVN.

The Java code is generated by invoking a bat fragment that generates Java based on Proto.

The generated Java code is submitted to the service-side backbone via SVN.

So, now that you're ready to write the proto file, and then double-click the bat, you can update SVN to get the latest Protobuf data object.


Bat Run


Generate CS files based on Proto and compile two vs projects, then submit the generated DLL to SVN


Generate Java code and submit SVN

This step related to the operation of the people are interested to try their own, there are questions Welcome to discuss this blog.

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.