client.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2021 the gRPC authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <iostream>
  15. #include <memory>
  16. #include <string>
  17. #include "examples/protos/helloworld.grpc.pb.h"
  18. #include <grpcpp/grpcpp.h>
  19. using grpc::Channel;
  20. using grpc::ClientContext;
  21. using grpc::Status;
  22. using helloworld::Greeter;
  23. using helloworld::HelloReply;
  24. using helloworld::HelloRequest;
  25. class GreeterClient {
  26. public:
  27. GreeterClient(std::shared_ptr<Channel> channel)
  28. : stub_(Greeter::NewStub(channel)) {}
  29. std::string SayHello(const std::string& user) {
  30. HelloRequest request;
  31. request.set_name(user);
  32. HelloReply reply;
  33. ClientContext context;
  34. Status status = stub_->SayHello(&context, request, &reply);
  35. if (status.ok()) {
  36. return reply.message();
  37. }
  38. std::cout << status.error_code() << ": " << status.error_message()
  39. << std::endl;
  40. return "RPC failed";
  41. }
  42. private:
  43. std::unique_ptr<Greeter::Stub> stub_;
  44. };
  45. int main(int argc, char** argv) {
  46. std::string target_str("unix-abstract:grpc%00abstract");
  47. GreeterClient greeter(
  48. grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
  49. std::string user("arst");
  50. std::cout << "Sending '" << user << "' to " << target_str << " ... ";
  51. std::string reply = greeter.SayHello(user);
  52. std::cout << "Received: " << reply << std::endl;
  53. return 0;
  54. }