gRPC server in a WorkerService
A few days ago, I was working on a client-server application where I was going to use Sockets to establish communication. But then I had the idea that I could use gRPC, which would expand the range of possible clients. Plus, it would serve as a learning experience for me to use gRPC.
The first surprise was that Visual Studio only offers a gRPC template that requires an ASP.Net server. So, I decided to do some research since my application would use a WorkerService that would likely run as a Docker image.
After doing a little research, I decided to start testing, and this is the result.
Server
The first step is to generate a WorkerService application in Visual Studio. Then, the following Nuget packages in their most updated version should be added:
<PackageReference include="Grpc" version="2.46.6">
<PackageReference include="Google.Protobuf" version="3.22.1">
<PackageReference Include="Grpc.Tools" Version="2.53.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference>
Next, we will create a folder called Protos or Proto, whichever you prefer. And a new .proto file with the service definition.
We will add this file to the project.
<ItemGroup>
<Protobuf Include="Proto\my_file.proto" />
</ItemGroup>
syntax = "proto3";
import "google/protobuf/empty.proto";
option csharp_namespace = "GrpcServer";
message CommandRequest {
int32 id = 1;
string params = 2;
}
message CommandResponse {
string message = 1;
}
service CommsService {
rpc SendCommand (CommandRequest) returns (CommandResponse);
}
Next, we create the class to manage the service.
public partial class CommsService : SysmacGrpcServer.CommsService.CommsServiceBase {
public override Task<CommandResponse> SendCommand(CommandRequest request, ServerCallContext context) {
CommandResponse response = new CommandResponse() {Message = "Message received"};
return Task.FromResult(response);
}
}
As a final step, we will start the server in the WorkerService.
public class SysmacWorker : BackgroundService {
private readonly Server _server;
public SysmacWorker(CommsService commService) {
_commsService = commService;
_server = new Server {
Services = { SysmacGrpcServer.CommsService.BindService(_commsService) },
Ports = { new ServerPort("localhost", 50051, ServerCredentials.Insecure) }
};
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
_server.Start();
await Task.Delay(100, stoppingToken);
}
}
Comments
Post a Comment