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