greeter_async_client2.cc 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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::Channel;
  30. using grpc::ClientAsyncResponseReader;
  31. using grpc::ClientContext;
  32. using grpc::CompletionQueue;
  33. using grpc::Status;
  34. using helloworld::Greeter;
  35. using helloworld::HelloReply;
  36. using helloworld::HelloRequest;
  37. class GreeterClient {
  38. public:
  39. explicit GreeterClient(std::shared_ptr<Channel> channel)
  40. : stub_(Greeter::NewStub(channel)) {}
  41. // Assembles the client's payload and sends it to the server.
  42. void SayHello(const std::string& user) {
  43. // Data we are sending to the server.
  44. HelloRequest request;
  45. request.set_name(user);
  46. // Call object to store rpc data
  47. AsyncClientCall* call = new AsyncClientCall;
  48. // stub_->PrepareAsyncSayHello() creates an RPC object, returning
  49. // an instance to store in "call" but does not actually start the RPC
  50. // Because we are using the asynchronous API, we need to hold on to
  51. // the "call" instance in order to get updates on the ongoing RPC.
  52. call->response_reader =
  53. stub_->PrepareAsyncSayHello(&call->context, request, &cq_);
  54. // StartCall initiates the RPC call
  55. call->response_reader->StartCall();
  56. // Request that, upon completion of the RPC, "reply" be updated with the
  57. // server's response; "status" with the indication of whether the operation
  58. // was successful. Tag the request with the memory address of the call
  59. // object.
  60. call->response_reader->Finish(&call->reply, &call->status, (void*)call);
  61. }
  62. // Loop while listening for completed responses.
  63. // Prints out the response from the server.
  64. void AsyncCompleteRpc() {
  65. void* got_tag;
  66. bool ok = false;
  67. // Block until the next result is available in the completion queue "cq".
  68. while (cq_.Next(&got_tag, &ok)) {
  69. // The tag in this example is the memory location of the call object
  70. AsyncClientCall* call = static_cast<AsyncClientCall*>(got_tag);
  71. // Verify that the request was completed successfully. Note that "ok"
  72. // corresponds solely to the request for updates introduced by Finish().
  73. GPR_ASSERT(ok);
  74. if (call->status.ok())
  75. std::cout << "Greeter received: " << call->reply.message() << std::endl;
  76. else
  77. std::cout << "RPC failed" << std::endl;
  78. // Once we're complete, deallocate the call object.
  79. delete call;
  80. }
  81. }
  82. private:
  83. // struct for keeping state and data information
  84. struct AsyncClientCall {
  85. // Container for the data we expect from the server.
  86. HelloReply reply;
  87. // Context for the client. It could be used to convey extra information to
  88. // the server and/or tweak certain RPC behaviors.
  89. ClientContext context;
  90. // Storage for the status of the RPC upon completion.
  91. Status status;
  92. std::unique_ptr<ClientAsyncResponseReader<HelloReply>> response_reader;
  93. };
  94. // Out of the passed in Channel comes the stub, stored here, our view of the
  95. // server's exposed services.
  96. std::unique_ptr<Greeter::Stub> stub_;
  97. // The producer-consumer queue we use to communicate asynchronously with the
  98. // gRPC runtime.
  99. CompletionQueue cq_;
  100. };
  101. int main(int argc, char** argv) {
  102. // Instantiate the client. It requires a channel, out of which the actual RPCs
  103. // are created. This channel models a connection to an endpoint (in this case,
  104. // localhost at port 50051). We indicate that the channel isn't authenticated
  105. // (use of InsecureChannelCredentials()).
  106. GreeterClient greeter(grpc::CreateChannel(
  107. "localhost:50051", grpc::InsecureChannelCredentials()));
  108. // Spawn reader thread that loops indefinitely
  109. std::thread thread_ = std::thread(&GreeterClient::AsyncCompleteRpc, &greeter);
  110. for (int i = 0; i < 100; i++) {
  111. std::string user("world " + std::to_string(i));
  112. greeter.SayHello(user); // The actual RPC call!
  113. }
  114. std::cout << "Press control-c to quit" << std::endl << std::endl;
  115. thread_.join(); // blocks forever
  116. return 0;
  117. }