11

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 ?
damleak
  • 549
  • 1
  • 5
  • 20

1 Answers1

20

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();
...
forkbong
  • 316
  • 3
  • 6
  • could you expand on this? is there a code example that does this? I'm trying to create an AsyncServer that does something like what you're describing with multiple types of completely different RPC calls. – davidawad Apr 17 '19 at 15:23
  • 4
    @davidawad You can take a look [here](https://github.com/forkbong/crocks/blob/master/src/server/async_server.cc). This is a project I was working on at the time I wrote the answer, and it does what I'm describing. I suggest you start with [this commit](https://github.com/forkbong/crocks/commit/a74d92f055f4d3aa4646bb6709e7174b340523a5), which introduces the asynchronous server and is much simpler. If you need further help feel free to ask, but I haven't written any C++ since then, and I'm not sure if I'll be able to help. – forkbong Apr 18 '19 at 17:15