greeter_server.cc 2.3 KB

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