[Network Communication] Unity uses protobuf to build a simple double-ended communication model

foreword

When using server communication, the routine is to use Google's Protobuf protocol format to serialize data.
The simple two-terminal interaction of Unity on the Internet rarely involves protobuf. Here is a simple demo that includes the use of Protobuf.
The focus of this model is to explain how to use protobuf, so the network-related functions are only implemented. If necessary, you can understand the relevant details and rewrite them yourself.

project

Test version: 2018.3.8f1
NetDemo.unitypackage
insert image description here

Protobuf uses

  1. Define the protocol, then use the protoc tool to generate usable code
  2. Registration Agreement

generate agreement

insert image description here

  • The file
    protoc.exe is a protocol converter provided by Google, which needs to be invoked in the form of a command line.
    GenProtoc.bat is a command line script that I encapsulated, which can generate the source protocol placed in the source to the gen folder.

  • The folder
    source folder contains protocol files in proto format. The gen folder is the converted code.
    Pay attention to the format when defining the protocol. For example, int is not acceptable, and it must be written clearly as int32. For details, please refer to Baidu's "protobuf protocol".
    insert image description hereinsert image description here

Registration Agreement

Registration requires two steps:

  1. command and interpreter. Both values ​​are automatically generated by protobuf. The specific code is in the gen folder.
  2. command and processing callbacks. The processing callback is the business code, which needs to be written by yourself. The data can be manipulated in the business callback code.

insert image description here

business

  • Receiving
    Following the above picture, here is the received information, protobuf has deserialized the data, just change the type when using it.
    insert image description here
  • Send
    new an object, and then assign it. It can be sent according to the command. Be careful not to write the command wrong, otherwise the other party will receive it wrong. (This big pit is not easy to check, blood and tears lesson..
    insert image description here

plug-in

To use protobuf, you must install the GoogleProtobuf plug-in. It has been collected in the demo, you can check it out for yourself.

network model

The same point of both ends is sending and receiving and filling and parsing of the packet body, so this point can be combined together. The rest of the business processing needs to be inherited and rewritten respectively.
insert image description here

Guess you like

Origin blog.csdn.net/sinat_34870723/article/details/103303266