Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gRPC multiple services in cpp async server

Tags:

grpc

I know there is an example helloworld program in gRPC source. However, being new to this, I don't understand how to write more than one async services in the server. The example here talks about spawning new instances of a class to handle SayHello service calls.

  1. How to add new services, for example SayBye, so that I can make calls to it from client?
  2. How to make the server identify which service call was made by the client ?
like image 725
damleak Avatar asked Jan 19 '17 02:01

damleak


1 Answers

See this thread and the relevant example. The suggestion is to add a bool parameter to CallData (hello_ in this example), instantiate two CallData objects, one with hello_ = true, and one with hello_ = false, and have each one request a different RPC.

if (hello_) {
  service_->RequestSayHello(...);
} else {
  service_->RequestSayBye(...);
}

For more than two types of calls, you could achieve the same behavior with an enum instead of a bool.

A more flexible approach would be to have a different CallData-like class for each RPC. However when you get a tag from cq_->Next(), you know that it is a pointer to an object of one of these classes, but you don't know its exact type. To overcome this, you can have them all inherit from a class with a virtual Proceed() member function, implement it as needed in each subclass, and when you get a tag, cast it as CallData and call Proceed().

class CallData {
 public:
  virtual void Proceed() = 0;
};

class HelloCallData final : public CallData {...};
class ByeCallData final : public CallData {...};

...
new HelloCallData(...);
new ByeCallData(...);
cq_->Next(&tag, &ok);
static_cast<CallData*>(tag)->Proceed();
...
like image 171
forkbong Avatar answered Oct 14 '22 06:10

forkbong