Skip to content

vkardon/grpc_async_server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

grpc_async_server

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):

  1. 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.

  2. Add method in your derived class for each RPC method defined in your service definition.

  3. 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)
    {
        ...
    }
};
  1. Derive your server class from gen::GrpcServer.
  2. Override OnInit() method to add all supported services.
  3. 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.

About

Headers-only C++ library for building asynchronous gRPC servers

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published