Skip to content

2. Add a new service

Geoffrey Pruvost edited this page Jul 31, 2017 · 5 revisions

Deprecated with the beta version v0.2

There are 3 steps to add a new service in the API.

A hello world example is available in the git branch documentation/add_a_new_service

1. Add the protobuf file

Your protobuf file must to be in the folder protos, for the example the file is helloworld.proto

syntax = "proto3";

package example;

service HelloWorldService {
    rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
    string message = 1;
}

message HelloResponse {
    string message = 2;
}

To compile your protobuf file, update the file CMakeLists.txt :

  • after line 31 section add the new protobuf file in a variable, for the example the variable name is PROTO_FILE_HELLO and the file is located at /protos/helloworld.proto :

set(PROTO_FILE_HELLO ${CMAKE_CURRENT_SOURCE_DIR}/protos/helloworld.proto)

  • at line 34 and 35 add your file variable at the end of the functions protobuf_generate_cpp and grpc_generate_cpp:
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS ${PROTO_SRC_DIR} ${PROTO_FILE_HCFI} ${PROTO_FILE_HELLO})
grpc_generate_cpp(GRPC_SRCS GRPC_HDRS ${PROTO_SRC_DIR} ${PROTO_FILE_HCFI} ${PROTO_FILE_HELLO})

To compile the protobuff file and generate the new c++ files go in the build folder and run :
cmake ..
make

2. Implement the new grpc service

Now we need to implement the new service. Add the .h and the .cpp file in the folder grpcServices.

For the example we add HelloWorld.h and HelloWorld.cpp
The new service extends the service class generated and located in protoClassServer/<name_of_proto_file>.grpc.pb.h

example files :

3. Register the new service

We need now to register the new service in the server.cpp file.

Include the service : #include "grpcServices/HelloWorld.h"

Instantiate the service : HelloWorld helloWorldService;

And finally register the service by using the serverBuilder method : builder.RegisterService(&helloWorldService);

Example file : Server.cpp

Clone this wiki locally