xref: /aosp_15_r20/external/grpc-grpc/examples/cpp/generic_api/greeter_server.cc (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Copyright 2023 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 #include <unordered_set>
19 
20 #include "absl/flags/flag.h"
21 #include "absl/flags/parse.h"
22 #include "absl/strings/str_format.h"
23 #include "absl/synchronization/mutex.h"
24 
25 #include <grpcpp/grpcpp.h>
26 #include <grpcpp/health_check_service_interface.h>
27 
28 #ifdef BAZEL_BUILD
29 #include "examples/protos/helloworld.grpc.pb.h"
30 #else
31 #include "helloworld.grpc.pb.h"
32 #endif
33 
34 ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
35 
36 using grpc::ByteBuffer;
37 using grpc::CallbackGenericService;
38 using grpc::CallbackServerContext;
39 using grpc::GenericCallbackServerContext;
40 using grpc::ProtoBufferReader;
41 using grpc::ProtoBufferWriter;
42 using grpc::Server;
43 using grpc::ServerBuilder;
44 using grpc::ServerGenericBidiReactor;
45 using grpc::Status;
46 using grpc::StatusCode;
47 using helloworld::HelloReply;
48 using helloworld::HelloRequest;
49 
50 // Logic and data behind the server's behavior.
51 class GreeterServiceImpl final : public CallbackGenericService {
CreateReactor(GenericCallbackServerContext * context)52   ServerGenericBidiReactor* CreateReactor(
53       GenericCallbackServerContext* context) override {
54     if (context->method() == "/helloworld.Greeter/SayHello") {
55       // Let the SayHello reactor handle this now on.
56       return new SayHelloReactor();
57     } else {
58       // Forward this to the implementation of the base calss returning
59       // UNIMPLEMENTED.
60       return CallbackGenericService::CreateReactor(context);
61     }
62   }
63 
64   class SayHelloReactor : public ServerGenericBidiReactor {
65    public:
SayHelloReactor()66     SayHelloReactor() { StartRead(&request_); }
67 
68    private:
OnSayHello(const HelloRequest & request,HelloReply * reply)69     Status OnSayHello(const HelloRequest& request, HelloReply* reply) {
70       if (request.name() == "") {
71         return Status(StatusCode::INVALID_ARGUMENT, "name is not specified");
72       }
73       reply->set_message(absl::StrFormat("Hello %s", request.name()));
74       return Status::OK;
75     }
76 
OnDone()77     void OnDone() override { delete this; }
OnReadDone(bool ok)78     void OnReadDone(bool ok) override {
79       if (!ok) {
80         return;
81       }
82       Status result;
83       // Deserialize a request message
84       HelloRequest request;
85       result = grpc::GenericDeserialize<ProtoBufferReader, HelloRequest>(
86           &request_, &request);
87       if (!result.ok()) {
88         Finish(result);
89         return;
90       }
91       // Call the SayHello handler
92       HelloReply reply;
93       result = OnSayHello(request, &reply);
94       if (!result.ok()) {
95         Finish(result);
96         return;
97       }
98       // Serialize a reply message
99       bool own_buffer;
100       result = grpc::GenericSerialize<ProtoBufferWriter, HelloReply>(
101           reply, &response_, &own_buffer);
102       if (!result.ok()) {
103         Finish(result);
104         return;
105       }
106       StartWrite(&response_);
107     }
OnWriteDone(bool ok)108     void OnWriteDone(bool ok) override {
109       Finish(ok ? Status::OK
110                 : Status(StatusCode::UNKNOWN, "Unexpected failure"));
111     }
112     ByteBuffer request_;
113     ByteBuffer response_;
114   };
115 
116  private:
117   absl::Mutex mu_;
118 };
119 
RunServer(uint16_t port)120 void RunServer(uint16_t port) {
121   std::string server_address = absl::StrFormat("0.0.0.0:%d", port);
122   GreeterServiceImpl service;
123   grpc::EnableDefaultHealthCheckService(true);
124   ServerBuilder builder;
125   // Listen on the given address without any authentication mechanism.
126   builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
127   // Register "service" as the instance through which we'll communicate with
128   // clients. In this case it corresponds to an *synchronous* service.
129   builder.RegisterCallbackGenericService(&service);
130   // Finally assemble the server.
131   std::unique_ptr<Server> server(builder.BuildAndStart());
132   std::cout << "Server listening on " << server_address << std::endl;
133 
134   // Wait for the server to shutdown. Note that some other thread must be
135   // responsible for shutting down the server for this call to ever return.
136   server->Wait();
137 }
138 
main(int argc,char ** argv)139 int main(int argc, char** argv) {
140   absl::ParseCommandLine(argc, argv);
141   RunServer(absl::GetFlag(FLAGS_port));
142   return 0;
143 }
144