Kindly refer to earlier post, where I have explained gRPC in detailed and have created a gRPC server application.
Here we are going to create a gRPC client application. For that we will create a console application and add following packages.
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.22.1" />
<PackageReference Include="Grpc.Net.Client" Version="2.51.0" />
<PackageReference Include="Grpc.Net.Client.Web" Version="2.51.0" />
<PackageReference Include="Grpc.Tools" Version="2.52.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
Now add a new Protos
folder and create a new empty file named company.proto.
gRPC Service
In the application, open the program.cs
file and create a method for adding the Company & Employee details. We will call this method from the Main()
function.
Here we will create a gRPC channel with gRPC Server's remote URL that will communicate with the gRPC server. After that we will have to create Employee
and Company
objects to pass it with the service.
var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
{
HttpHandler = new GrpcWebHandler(new HttpClientHandler())
});
var readerClient = new Company.CompanyClient(channel);
//Creating new employees
var employees = new EmployeeModel[]
{
new EmployeeModel
{
EmpId = 1,
EmpName = "Rama Bapat",
BirthDate = Timestamp.FromDateTime(DateTime.UtcNow.AddYears(-24).AddMonths(-4)),
CompanyId = 1
},
new EmployeeModel
{
EmpId = 2,
EmpName = "Krishna Nene",
BirthDate = Timestamp.FromDateTime(DateTime.UtcNow.AddYears(-22).AddMonths(-7)),
CompanyId = 1
}
};
//Creating new company
var company = new CompanyModel
{
CompanyId = 1,
ComapnyName = "Patankar Khauwale"
};
//Adding employees to company model
company.Employees.Add(employees);
//Calling the server channel
var responseData = await readerClient.PostCompanyWithEmployeesAsync(company);
if (responseData.Status == 1)
{
Console.WriteLine("Company & Employees added Successfully.");
}
else
{
Console.WriteLine("Company & Employees could not be added, please try again.");
}
Now, just save and build the application. Following line will get added .csproj
file.
<ItemGroup>
<Protobuf Include="Protos\company.proto" GrpcServices="Client" />
</ItemGroup>
Once all is done, we will run both the applications and call the Server and we should get a response from the it. In our case the Server
will respond with an integer. We’ll see the results in console output window.
Congratulations! We just successfully built a Client
and Server
gRPC application.
References
- Git repository for gRPC Client application
- Git repository gRPC Server application
- Official gRPC site
- Microsoft's documentation for gRPC on .Net Core
Cover photo by Karim MANJRA on Unsplash
Top comments (0)