greeter_async_server.cc 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /*
  2. *
  3. * Copyright 2015 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <iostream>
  19. #include <memory>
  20. #include <string>
  21. #include <thread>
  22. #include <grpc/support/log.h>
  23. #include <grpcpp/grpcpp.h>
  24. #ifdef BAZEL_BUILD
  25. #include "examples/protos/helloworld.grpc.pb.h"
  26. #else
  27. #include "helloworld.grpc.pb.h"
  28. #endif
  29. using grpc::Server;
  30. using grpc::ServerAsyncResponseWriter;
  31. using grpc::ServerBuilder;
  32. using grpc::ServerCompletionQueue;
  33. using grpc::ServerContext;
  34. using grpc::Status;
  35. using helloworld::Greeter;
  36. using helloworld::HelloReply;
  37. using helloworld::HelloRequest;
  38. class ServerImpl final {
  39. public:
  40. ~ServerImpl() {
  41. server_->Shutdown();
  42. // Always shutdown the completion queue after the server.
  43. cq_->Shutdown();
  44. }
  45. // There is no shutdown handling in this code.
  46. void Run() {
  47. std::string server_address("0.0.0.0:50051");
  48. ServerBuilder builder;
  49. // Listen on the given address without any authentication mechanism.
  50. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  51. // Register "service_" as the instance through which we'll communicate with
  52. // clients. In this case it corresponds to an *asynchronous* service.
  53. builder.RegisterService(&service_);
  54. // Get hold of the completion queue used for the asynchronous communication
  55. // with the gRPC runtime.
  56. cq_ = builder.AddCompletionQueue();
  57. // Finally assemble the server.
  58. server_ = builder.BuildAndStart();
  59. std::cout << "Server listening on " << server_address << std::endl;
  60. // Proceed to the server's main loop.
  61. HandleRpcs();
  62. }
  63. private:
  64. // Class encompasing the state and logic needed to serve a request.
  65. class CallData {
  66. public:
  67. // Take in the "service" instance (in this case representing an asynchronous
  68. // server) and the completion queue "cq" used for asynchronous communication
  69. // with the gRPC runtime.
  70. CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq)
  71. : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) {
  72. // Invoke the serving logic right away.
  73. Proceed();
  74. }
  75. void Proceed() {
  76. if (status_ == CREATE) {
  77. // Make this instance progress to the PROCESS state.
  78. status_ = PROCESS;
  79. // As part of the initial CREATE state, we *request* that the system
  80. // start processing SayHello requests. In this request, "this" acts are
  81. // the tag uniquely identifying the request (so that different CallData
  82. // instances can serve different requests concurrently), in this case
  83. // the memory address of this CallData instance.
  84. service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
  85. this);
  86. } else if (status_ == PROCESS) {
  87. // Spawn a new CallData instance to serve new clients while we process
  88. // the one for this CallData. The instance will deallocate itself as
  89. // part of its FINISH state.
  90. new CallData(service_, cq_);
  91. // The actual processing.
  92. std::string prefix("Hello ");
  93. reply_.set_message(prefix + request_.name());
  94. // And we are done! Let the gRPC runtime know we've finished, using the
  95. // memory address of this instance as the uniquely identifying tag for
  96. // the event.
  97. status_ = FINISH;
  98. responder_.Finish(reply_, Status::OK, this);
  99. } else {
  100. GPR_ASSERT(status_ == FINISH);
  101. // Once in the FINISH state, deallocate ourselves (CallData).
  102. delete this;
  103. }
  104. }
  105. private:
  106. // The means of communication with the gRPC runtime for an asynchronous
  107. // server.
  108. Greeter::AsyncService* service_;
  109. // The producer-consumer queue where for asynchronous server notifications.
  110. ServerCompletionQueue* cq_;
  111. // Context for the rpc, allowing to tweak aspects of it such as the use
  112. // of compression, authentication, as well as to send metadata back to the
  113. // client.
  114. ServerContext ctx_;
  115. // What we get from the client.
  116. HelloRequest request_;
  117. // What we send back to the client.
  118. HelloReply reply_;
  119. // The means to get back to the client.
  120. ServerAsyncResponseWriter<HelloReply> responder_;
  121. // Let's implement a tiny state machine with the following states.
  122. enum CallStatus { CREATE, PROCESS, FINISH };
  123. CallStatus status_; // The current serving state.
  124. };
  125. // This can be run in multiple threads if needed.
  126. void HandleRpcs() {
  127. // Spawn a new CallData instance to serve new clients.
  128. new CallData(&service_, cq_.get());
  129. void* tag; // uniquely identifies a request.
  130. bool ok;
  131. while (true) {
  132. // Block waiting to read the next event from the completion queue. The
  133. // event is uniquely identified by its tag, which in this case is the
  134. // memory address of a CallData instance.
  135. // The return value of Next should always be checked. This return value
  136. // tells us whether there is any kind of event or cq_ is shutting down.
  137. GPR_ASSERT(cq_->Next(&tag, &ok));
  138. GPR_ASSERT(ok);
  139. static_cast<CallData*>(tag)->Proceed();
  140. }
  141. }
  142. std::unique_ptr<ServerCompletionQueue> cq_;
  143. Greeter::AsyncService service_;
  144. std::unique_ptr<Server> server_;
  145. };
  146. int main(int argc, char** argv) {
  147. ServerImpl server;
  148. server.Run();
  149. return 0;
  150. }