The application of grpc in C# and Unity

Recently, a unity project of the company wanted to replace the communication method from Photon to grpc, just to learn grpc systematically. The following is my learning experience.

This blog system introduces all the main points of unity using grpc communication in detail, and I hope it can help everyone. Ollie give it!

1. Introduction to the knowledge points of this blog

Reading this blog can gain the following technical knowledge;

  1. Define service
  2. Use GRPC.Tools automatic code to parse .proto into .cs
  3. Create server and client
  4. Use Grpc in C#
  5. Use Grpc in Unity

2. Download address of resources and tools

1. Each version of protocolBuffers

Download link : https://github.com/protocolbuffers/protobuf
There are many versions of protoBuf. Which version of the .proto in the project uses will be resolved by which version. If there is no requirement, it is recommended to download 3.8.x, because currently Grpc C# is for Unity It is still experimentally supported , and the version used is 3.8.

Insert picture description here
Download according to the following options:

Insert picture description here
Then find a document, save it, and decompress it:
Insert picture description here
Protocol buffers is a flexible, efficient, and automated protocol for serializing structured data. Compared with XML, the serialized code stream of Protocol buffers is smaller and faster. Faster and easier to operate.

(To be distinguished from Protocol, the rules, standards, or conventions established by Protocol for data exchange in the network are a set of rules that control the data exchange between two entities.)

You only need to define the data structure to be serialized once (using the .proto file definition), and then you can use the specially generated source code (using the generation tool provided by protobuf) to easily use different data streams to complete the reading of these structured data Write operation, even if you use a different language (protobuf's cross-language support feature)

This blog only introduces how to use protocolBuffers. If you want to learn more about the principle, you can read this blog: Portal

2、GRPC

GRPC is a high-performance, open source and universal RPC (Remote Procedure Call Protocol) framework, based on the ProtoBuf (ProtocolBuffers) serialization protocol development, and supports many development languages.

Download link: https://github.com/grpc/grpc

Insert picture description here
Also find a file, save it, and unzip it. At this time, we download all platforms corresponding to grpc, and the official cases of C# and unity are in this path:

Insert picture description here

3、grpc_unity_package.2.27.0-dev

In order to realize untiy network communication conveniently and quickly, grpc directly provides the .dll needed for unity communication (the Google.protobuf version contained in it is 3.8), which can be downloaded directly into the plugins folder of unity for interface reference.

Download link: https://packages.grpc.io/archive/2019/12/e522302e33b2420722f866e3de815e4e0a1d9952-219973fd-1007-4db7-a78f-976ec554952d/index.xml

Insert picture description here

4. .NET Core SDK 2.1 and above

When using grpc and protobuf, the computer environment needs to be .NET Core SDK 2.1 and above. Download the corresponding sdk and Runtime according to your VS version. After downloading, it is .exe, double-click to install it.
Insert picture description here

Of course, in addition, you must have the corresponding version of VisualStudio and Unity
.

Three, C# uses the Grpc method process

1. New project

Insert picture description here
Then under the current solution, add two console applications grpcServer and grpcClient.

Insert picture description here
The new solution is as follows:

Insert picture description here

2. Define the service

Define the service, that is, use the proto syntax to write the interface and call grpc. Here we add a .proto script to the grpcTest project for parsing into .cs.
Click Add -> New Project, directly fill in the name: test.proto, the content is as follows, copy it to the script.


syntax ="proto3";
packagegrpcTesst;
 
servicegRPC {
    
    
  rpc SayHello (TestRequest) returns(TestReply) {
    
    }
}
 
messageTestRequest {
    
    
  string name = 1;
}
 
messageTestReply {
    
    
  string message = 1;
}

The test.proto file is best placed in this directory, so that beginners can directly use the command line I gave ( currently you do not have test.cs and testGrpc.cs ).

Insert picture description here

For the detailed method of grpc, if you want to know the Chinese version of the official gRPC document: http://doc.oschina.net/grpc?t=60132 ,
you can also refer to this blog: https://blog.csdn.net/qq_28110727/ article/details/78984746
.

3. Use GRPC.Tools to automatically generate .cs code

The last step of the service definition is successful, and then import the relevant package in the project, and then use GRPC.Tools to automatically parse test.pproto into .cs code.

1. Add Grpc and Google.Protobuf
NuGet command lines to each project (grpctest, grpcServer, grpcClient) (View -> Other windows -> Package Manager console):

Install-Package Grpc
Install-Package Google.Protobuf

Insert picture description here
Enter the NuGet command line and press Enter.
Insert picture description here
You can switch projects directly here
Insert picture description here

Insert picture description here
2. Then add the tool Grpc.Tools to the grpcTest project (to generate source files)

Install-Package Grpc.Tools

Insert picture description here
3. Next, use GRPC.Tools to automatically parse test.proto into .cs code

After the upper operation is completed, you can see that various package bodies are imported into the grpcTest\packages folder. Pay attention to the version of Grpc.Tools. Mine is Grpc.Tools.2.32.0.

Insert picture description here
Run cmd and cd commands in the system to enter our project folder, which is the upper level of packages, and then write the following commands and run them.
(The version number of Grpc.Tools, project name grpcTest, test.proto should be replaced with the corresponding names in your own project).

packages\Grpc.Tools.2.32.0\tools\windows_x86\protoc.exe -IgrpcTest --csharp_out grpcTest  grpcTest\test.proto --grpc_out grpcTest --plugin=protoc-gen-grpc=packages\Grpc.Tools.2.32.0\tools\windows_x86\grpc_csharp_plugin.exe

Insert picture description here

Enter the command and press Enter. You can find that there are two additional classes, test.cs and testGrpc.cs, in the grpcTest\grpcTest directory. This is the .cs code parsed by test.proto, which contains the interface called by the client.

Insert picture description here
4. Add the generated class to the project and add references

Now include the Test.cs and TestGrpc.cs classes into the grpcTest project.
Right-click on the project -> Add -> Existing items and select Test.cs and TestGrpc.cs files
after adding them as follows:
Insert picture description here
then grpcServer and grpcClient respectively refer to grpcTest.
(Right click on the project reference node -> add reference -> select project under the project solution)
Insert picture description here
as follows, the reference is added successfully.

Insert picture description here

4. Create server and client

Let's write the server and client.
1. Server:
Press F2 to rename the default Program.cs file to TestServer.cs (Note: If you operate on the solution panel, you will be prompted whether to modify the related references at the same time, choose Yes!)


usingGrpc.Core;
usingGrpcTesst;
usingSystem;
usingSystem.Threading.Tasks;
 
namespacegrpcServer
{
    
    
    class gRPCImpl : gRPC.gRPCBase
    {
    
    
        // 实现SayHello方法
        public override Task<TestReply>SayHello(TestRequest request, ServerCallContext context)
        {
    
    
            return Task.FromResult(newTestReply {
    
     Message = "Hello " + request.Name });
        }
    }
 
    class TestServer
    {
    
    
        const int Port = 9007;
 
        public static void Main(string[] args)
        {
    
    
            Server server = new Server
            {
    
    
                Services= {
    
     gRPC.BindService(new gRPCImpl()) },
                Ports = {
    
     newServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();
 
            Console.WriteLine("gRPC serverlistening on port " + Port);
           Console.WriteLine("任意键退出...");
            Console.ReadKey();
 
            server.ShutdownAsync().Wait();
        }
    }
}

2. Client:
Press F2 to rename the default Program.cs file to TestClient.cs (Note: If you operate on the solution panel, you will be prompted whether to modify the related references at the same time, choose Yes!)


usingGrpc.Core;
usingGrpcTesst;
usingSystem;
 
namespacegrpcClient
{
    
    
    class TestClient
    {
    
    
        static void Main(string[] args)
        {
    
    
            Channel channel = newChannel("127.0.0.1:9007", ChannelCredentials.Insecure);
 
            var client = newgRPC.gRPCClient(channel);
            var reply = client.SayHello(newTestRequest {
    
     Name = "sunguangdong" });
           Console.WriteLine("来自" +reply.Message);
 
            channel.ShutdownAsync().Wait();
           Console.WriteLine("任意键退出...");
            Console.ReadKey();
        }
    }
}

5. Realize grpc communication

The previous operation created the client and server, and then you can try to communicate.
1. Right-click on these two items to generate.
Insert picture description here
After generation, you will see two more
.exes in this directory of the project (grpcClient\bin\Debug\grpcClient.exe)
(grpcServer\bin\Debug\grpcServer.exe)

Double-click to execute grpcServer.exe to start the local server, and then execute the grpcClient.exe client, as shown in the figure below, the communication is successful.
Insert picture description here

Fourth, use Grpc in Unity

Method 1 Import the generated .cs

1, create an empty Unity project, in File -> Build Settings -> Player Settings in the Api Compatibility Level (old version called Script Runtime Version) to .NET 4.x
Insert picture description here

3. Unzip the previously downloaded grpc_unity_package.zip to the Assets directory, namely the Plugins folder.

4. Copy Test.cs and TestGrpc.cs generated by the grpcTest project in the previous step to a folder of Assets

5. Create a new script GrpcTest.cs and hang it on any GameObject in the scene, add code in the Start() method, introduce grpc and other related libraries, and run the game.

using Grpc.Core;
using GrpcTest;

void Start()
{
    
    
        Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure);
        var client = new gRPC.gRPCClient(channel);
        var reply = client.SayHello(new TestRequest {
    
     Name = "sunguangdong" });
    	print("Greeting: " + reply.Message);
    	channel.ShutdownAsync().Wait();
}

Method 2 Import the generated .dll

The first 3 steps are the same as Method 1. Step 4:
Right-click the solution in VS to generate the solution. The generated grpcTest.dll can be found in this path of the grpcTest project folder.

grpcTest\grpcTest\bin\Debug\grpcTest.dll

Insert picture description here
Copy this file, paste it into the plugins folder of the unity project, and proceed as in step 5 of method 1.

Of course, you can also directly use the unity case provided by grpc, in this directory of the grpc file you downloaded earlier:
grpc-master\examples\csharp\HelloworldUnity
Insert picture description here

Five, matters needing attention and error solutions

1. Google.Protobuf version is inconsistent, the following error message is reported:
Insert picture description here

Because the unity case provided by grpc uses Google.Protobuf 3.8.0, if we want to directly use the official plugins, we need to use the same version in vs. When importing the package body in vs, download it directly in advance. ProtoBuf 3.8.0:
Insert picture description here
Open the reference in the grpcTest project, you can view the version:
Insert picture description here
right click to remove:

Insert picture description here
Then add a reference and manually specify the path, because the language is C#, so choose csharp, the path is as follows
protobuf-3.8.x\csharp\src\Google.Protobuf\bin\Debug\net45 After
Insert picture description here
Insert picture description here
replacing the reference, re-parse test.proto and generate Test .cs and TestGrpc.cs or grpcTest.dll.

2. Port problem The
above cases are connected to the local server. If you connect to a cloud server or a remote server, remember that the port number cannot be wrong.

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43505432/article/details/109243044