A headers-only C++ library to build asynchronous gRPC servers with support for unary, server-side streaming, and client-side streaming RPCs.
Environment: gRPC 1.60.0, GCC with C++17, Ubuntu 22.04, RedHat 7 & 8, or AlmaLinux 8 & 9.
You may need to adjust the Makefile to suit your build environment.
Basic example: (located in the 'example_basic' directory):
-
Derive your service class from gen::GrpcService<your_service>, where your_service is the namespace generated by the gRPC protocol buffer compiler (protoc) for your service definition.
-
Add method in your derived class for each RPC method defined in your service definition.
-
Override OnInit() method to bind every method in your derived class with the corresponding method defined in your service definition.
Example:
class HelloService : public gen::GrpcService<test::Hello>
{
public:
HelloService() = default;
virtual ~HelloService() = default;
// gen::GrpcService overrides
virtual bool OnInit() override
{
// Bind all HelloService RPCs
Bind(&HelloService::Ping, &HelloService::RequestPing);
Bind(&HelloService::Shutdown, &HelloService::RequestShutdown);
return true;
}
protected:
// Supported RPCs
void Ping(const gen::RpcContext& ctx,
const test::PingRequest& req, test::PingResponse& resp)
{
...
}
void Shutdown(const gen::RpcContext& ctx,
const test::ShutdownRequest& req, test::ShutdownResponse& resp)
{
...
}
};
- Derive your server class from gen::GrpcServer.
- Override OnInit() method to add all supported services.
- Build and start gRpc server.
Example:
class MyServer : public gen::GrpcServer
{
public:
MyServer() = default;
virtual ~MyServer() = default;
virtual bool OnInit(::grpc::ServerBuilder& /*builder*/) override
{
// Add all services
AddService<HelloService>();
return true;
}
};
int main(int argc, char* argv[])
{
// Build & start gRpc server.
MyServer srv;
srv.Run(PORT_NUMBER, 8 /*number of threads*/);
std::cout << "Grpc Server has stopped" << std::endl;
return 0;
}
Complete example: (located in the 'example_complete' directory):
This example illustrates a more sophisticated gRPC server and client implementation, demonstrating the use of the GrpcClient<> class.