Unity3d & Java based PROTOBUF communication implementation
A recent study of Unity3d, and the need to develop a communication protocol for the game. Because I was born at the back end, the socket-related communication framework for C # is not familiar, after a few days of learning, finally fix. Published here, we can learn together, less detours.
This article focuses on demonstrating how to parse and send protocols.
Technology selection
-
Service Side 1
-
Java7
-
Netty 4
-
Client 2
-
C #
-
Supersocket.clientengine https://clientengine.codeplex.com/
It is separated from the SuperSocket, the inhuman is actually did not use the tutorial
-
Communication Protocol 3
-
protobuf https://github.com/google/protobuf/
-
because PROTOBUF official only supports Java,c++,pythone languages, C # requires third-party support
-
protobuf-csharp https://code.google.com/p/protobuf-csharp-port/
Protobuf related use, please self-gooogle, the following code will show the relevant API, Goole can not open to buy an agent one months 20RMB
Preparation before development
The protocol parsing, regardless of any language protocol parsing in the communication is used is necessary. To successfully resolve the agreement, you must first understand how the agreement was formulated.
PROTOBUF is based on variable length message header (length) + Message body (body)
Proto generation
message Request { 1; 2;}message Response { 1; 2;}
As for how to generate, I do not give a detailed method here, through the PROTOBUF data, there is detailed description.
Client code
Public StaticDataeventargs buffer =NewDataeventargs (); Public Static intCount =0; Public Static void Main(string[] args) {buffer. Data =New byte[8192];//8 KBIPEndPoint EndPoint =NewIPEndPoint (Ipaddress.parse ("127.0.0.1"),8001);//supersocket ClientengineAsynctcpsession client =NewAsynctcpsession (EndPoint); Client. Connected + = onconnected; Client. DataReceived + = ondatareceive;//Focus on the analysis here //Connection ServerClient. Connect ();//construct message, attribute Protobuf people should be able to readRequest.builder Builder = Request.createbuilder (); Builder. SetCommand (" the"); Builder. SetData ("1231231232131"); Request Request = Builder. Buildpartial (); SendMessage (client, request); Thread.Sleep (30000); } Public Static void onconnected(Object sender, EventArgs e) {Console.WriteLine ("Connect to Server finish."); }/** * The implementation of C # here is the same as the Java implementation given by the PROTOBUF official */ Public Static void SendMessage(asynctcpsession client, request request) {using (MemoryStream stream =NewMemoryStream ()) {Codedoutputstream OS = codedoutputstream.createinstance (stream);//Be sure to look at its code implementation,Os. Writemessagenotag (Request);/** * Writemessagenotag equivalent to WriteVarint32, WriteByte (byte[]) * I.E.: variable length message header + message body */Os. Flush ();byte[] data = stream. ToArray (); Client. Send (Newarraysegment<byte> (data)); } }/** * Protocol resolution, the here to understand, there is no white see * * Public Static void ondatareceive(Object sender, Dataeventargs e) {//dataeventargs inside byte[] data is a byte array received from the protocol layer and needs to be cached by the terminalConsole.WriteLine ("Buff Length: {0}, offset: {1}", E.length, E.offset);if(E.length <=0) {return; }//Cache All the charges you have received in the local bufferArray.copy (E.data,0, buffer. Data, buffer. Length, e.length); Buffer. Length + = E.length; Codedinputstream stream = codedinputstream.createinstance (buffer. Data); while(!stream. Isatend) {//Tag read position, when the length is not enough to copy the array, to the next time to parse intMarkreadindex = (int) stream. Position;//protobuf The length of the head, that is, the message intVarint32 = (int) stream. ReadRawVarint32 ();if(Varint32 <= (buffer. Length-(int) stream. Position)) {Try{byte[] BODY = stream. Readrawbytes (Varint32); Response Response = Response.parsefrom (body); Console.WriteLine ("Response:"+ Response. ToString () +", Count:"+ (++count));//dispatcher message, where you can use multithreading for protocol distribution}Catch(Exception Exception) {Console.WriteLine (Exception). Message); } }Else{/** * This data is not sufficient length, the cache for the next parse * / byte[] Dest =New byte[8192];intremainsize = buffer. Length-markreadindex; Array.copy (buffer. Data, Markreadindex, dest,0, remainsize);/** * Cache Unhandled bytes */Buffer. Data = dest; Buffer. Offset =0; Buffer. Length = remainsize; Break; } } }
Postscript
Client complete code Package: http://download.csdn.net/detail/zeus_9i/8748899
- Unity3d Java based PROTOBUF communication implementation
- Technology selection
- Preparation before development
- Proto generation
- Client code
- Postscript
Unity3d & Java based PROTOBUF communication implementation