xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/unix_abstract_sockets/client.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
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 
15 #include <iostream>
16 #include <memory>
17 #include <string>
18 
19 #include "examples/protos/helloworld.grpc.pb.h"
20 
21 #include <grpcpp/grpcpp.h>
22 
23 using grpc::Channel;
24 using grpc::ClientContext;
25 using grpc::Status;
26 using helloworld::Greeter;
27 using helloworld::HelloReply;
28 using helloworld::HelloRequest;
29 
30 class GreeterClient {
31  public:
GreeterClient(std::shared_ptr<Channel> channel)32   GreeterClient(std::shared_ptr<Channel> channel)
33       : stub_(Greeter::NewStub(channel)) {}
34 
SayHello(const std::string & user)35   std::string SayHello(const std::string& user) {
36     HelloRequest request;
37     request.set_name(user);
38     HelloReply reply;
39     ClientContext context;
40     Status status = stub_->SayHello(&context, request, &reply);
41     if (status.ok()) {
42       return reply.message();
43     }
44     std::cout << status.error_code() << ": " << status.error_message()
45               << std::endl;
46     return "RPC failed";
47   }
48 
49  private:
50   std::unique_ptr<Greeter::Stub> stub_;
51 };
52 
main(int argc,char ** argv)53 int main(int argc, char** argv) {
54   std::string target_str("unix-abstract:grpc%00abstract");
55   GreeterClient greeter(
56       grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
57   std::string user("arst");
58   std::cout << "Sending '" << user << "' to " << target_str << " ... ";
59   std::string reply = greeter.SayHello(user);
60   std::cout << "Received: " << reply << std::endl;
61 
62   return 0;
63 }
64