Develop gRPC client in .NET 7.0

 

Table of Contents

1. Introduction 

2. Develop gRPC client in .NET 7

3. Test the client

4. Conclusion


Introduction 

gRPC (Google Remote Procedure Call) is an open-source high-performance framework developed by Google for building distributed systems.

In my previous post we talked about creating a gRPC service [Develop gRPC service in .NET 7.0]. This post will talk about developing a gRPC client in .NET 7 which will consume the gRPC service that was previously created.


Develop gRPC client in .NET 7

Create a new project in Visual Studio by using "Console App" template.



Give a name for the service and choose a location to save the project.



From the dropdown in the next screen choose .NET 7.0 and leave all other options with default value. Click on create button to create the project.





Add the following NuGet packages to the project.

1. Grpc.Net.Client
2. Google.Protobuf
3. Grpc.Tools





Create a folder in the project and name it "Protos" . Now copy "health.Protos" file to this folder which was created in my previous post for gRPC service. Edit and update this file and change "csharp_namespace" to "GrpcClient".



Right click on the "health.proto" file in the solution and open properties window. Set the value for 'Build Action' as 'Protobuf compiler' and value for 'gRPC Stub Classes' as 'Client only'.



Alternatively the properties can be set by editing the Project File and inserting an ItemGroup as below.

<ItemGroup> <Protobuf Include="Protos\health.proto" GrpcServices="Client" /> </ItemGroup>

Now build the project [Ctrl+Shift+B] which will generate C# code for the .proto file which can be used to implement your service.

Update the Program.cs file with the following code.


using Grpc.Net.Client;
using GrpcClient;
using var channel = GrpcChannel.ForAddress("http://localhost:4000");
var client = new HealthCheck.HealthCheckClient(channel);
var reply = await client.GetHealthAsync(new HealthRequest { });
Console.WriteLine("Response received : " + reply.Message);
Console.ReadKey();


Build the project and we are all done!

Test the client

Lets test the client now by running the gRPC service first [Please refer by previous post if you haven't created one yet]. Once the service is up and running the console shows a message similar to "Now listening on: http://0.0.0.0:4000". 4000 is the port number here which was configured in the service code.

Now RUN the gRPC client. Make sure to use the same port number on service and client.

We can now see that a communication is successfully established between gRPC service and client. The client console window now receives "Hello!!" message from server as response.





Conclusion

gRPC establishes a connection between service and client using HTTP2 protocol. The example used here uses http end point to be exposed and not https. To use https end point, a default certificate is required to be used to the minimum, by the gRPC service.

Comments