1 /*
2 *
3 * Copyright 2022 The 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
19 #include <iostream>
20 #include <memory>
21 #include <string>
22
23 #include <grpcpp/ext/proto_server_reflection_plugin.h>
24 #include <grpcpp/grpcpp.h>
25 #include <grpcpp/health_check_service_interface.h>
26
27 #include "protos/helloworld.grpc.pb.h"
28
29 using grpc::Server;
30 using grpc::ServerBuilder;
31 using grpc::ServerContext;
32 using grpc::Status;
33 using helloworld::Greeter;
34 using helloworld::HelloReply;
35 using helloworld::HelloRequest;
36
37 // Logic and data behind the server's behavior.
38 class GreeterServiceImpl final : public Greeter::Service {
SayHello(ServerContext * context,const HelloRequest * request,HelloReply * reply)39 Status SayHello(ServerContext* context, const HelloRequest* request,
40 HelloReply* reply) override {
41 std::string prefix("Hello ");
42 reply->set_message(prefix + request->name());
43 return Status::OK;
44 }
45 };
46
RunServer()47 void RunServer() {
48 std::string server_address("0.0.0.0:0");
49 GreeterServiceImpl service;
50
51 grpc::EnableDefaultHealthCheckService(true);
52 grpc::reflection::InitProtoReflectionServerBuilderPlugin();
53 ServerBuilder builder;
54 // Listen on the given address without any authentication mechanism.
55 int bound_port;
56 builder.AddListeningPort(server_address, grpc::InsecureServerCredentials(), &bound_port);
57 // Register "service" as the instance through which we'll communicate with
58 // clients. In this case it corresponds to an *synchronous* service.
59 builder.RegisterService(&service);
60 // Finally assemble the server.
61 std::unique_ptr<Server> server(builder.BuildAndStart());
62 std::cout << "127.0.0.1:" << bound_port << std::endl;
63
64 // Wait for the server to shutdown. Note that some other thread must be
65 // responsible for shutting down the server for this call to ever return.
66 server->Wait();
67 }
68
main(int argc,char ** argv)69 int main(int argc, char** argv) {
70 RunServer();
71
72 return 0;
73 }
74