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