Setting up the grpc server
Create a ASP.net core gRPC core service. Provide a name for it and then click "next" and complete the service creations.
The proto file looks something like this below:-
syntax = "proto3";
option csharp_namespace = "myGrpcService";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
You should be able to run the server and note down the expose endpoint. Please get the https://localhost:port-number.
Setting up the client
Create a console app and then add the following package.
Install-Package Grpc.Net.Client
Install-Package Google.Protobuf
Install-Package Grpc.Tools
Then add the proto file used in creating the server grpc server with minor updates to the namespace
syntax = "proto3";
option csharp_namespace = "GrpcGreeterClient";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}
Ensure you initial a project build - to generate the required code scaffold.
Then you can proceed to use the following code.
// See https://aka.ms/new-console-template for more information
using Grpc.Net.Client;
using GrpcGreeterClient;
Console.WriteLine("Hello, World!");
var channel = GrpcChannel.ForAddress("https://localhost:7294");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "World" });
Console.WriteLine(reply.Message);
Complete code
https://github.com/mitzenjeremywoo/grpc-tutorial
Comments