using grpc::Server; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::Status; using helloworld::Greeter; using helloworld::HelloReply; using helloworld::HelloRequest;
ABSL_FLAG(uint16_t, port, 50051, "Server port for the service");
// Logic and data behind the server's behavior. classGreeterServiceImplfinal : public Greeter::Service { Status SayHello(ServerContext* context, const HelloRequest* request, HelloReply* reply)override{ std::string prefix("Hello "); reply->set_message(prefix + request->name()); return Status::OK; } };
grpc::EnableDefaultHealthCheckService(true); grpc::reflection::InitProtoReflectionServerBuilderPlugin(); ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // Register "service" as the instance through which we'll communicate with // clients. In this case it corresponds to an *synchronous* service. builder.RegisterService(&service); // Finally assemble the server. std::unique_ptr<Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl;
// Wait for the server to shutdown. Note that some other thread must be // responsible for shutting down the server for this call to ever return. server->Wait(); }
using grpc::Channel; using grpc::ClientContext; using grpc::Status; using helloworld::Greeter; using helloworld::HelloReply; using helloworld::HelloRequest;
// Assembles the client's payload, sends it and presents the response back // from the server. std::string SayHello(const std::string& user){ // Data we are sending to the server. HelloRequest request; request.set_name(user);
// Container for the data we expect from the server. HelloReply reply;
// Context for the client. It could be used to convey extra information to // the server and/or tweak certain RPC behaviors. ClientContext context;
// The actual RPC. Status status = stub_->SayHello(&context, request, &reply);
// Act upon its status. if (status.ok()) { return reply.message(); } else { std::cout << status.error_code() << ": " << status.error_message() << std::endl; return"RPC failed"; } }
private: std::unique_ptr<Greeter::Stub> stub_; };
intmain(int argc, char** argv){ absl::ParseCommandLine(argc, argv); // Instantiate the client. It requires a channel, out of which the actual RPCs // are created. This channel models a connection to an endpoint specified by // the argument "--target=" which is the only expected argument. std::string target_str = absl::GetFlag(FLAGS_target); // We indicate that the channel isn't authenticated (use of // InsecureChannelCredentials()). GreeterClient greeter( grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials())); std::string user("world"); std::string reply = greeter.SayHello(user); std::cout << "Greeter received: " << reply << std::endl;
return0; }
运行
编译运行服务端,输出为
1 2 3 4 5 6
hyper372@hyper372-test:~/Documents/grpc/examples/cpp/helloworld/build$ ./greeter_callback_server WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1723773102.328242 4566 config.cc:257] gRPC experiments enabled: call_status_override_on_cancellation, call_tracer_in_transport, event_engine_dns, event_engine_listener, monitoring_experiment, pick_first_new, trace_record_callops, work_serializer_clears_time_cache I0000 00:00:1723773102.331365 4566 server_builder.cc:392] Synchronous server. Num CQs: 1, Min pollers: 1, Max Pollers: 2, CQ timeout (msec): 10000 I0000 00:00:1723773102.331432 4566 server_builder.cc:401] Callback server. Server listening on 0.0.0.0:50051
服务端运行,监听50051端口。
运行客户端,输出为:
1 2 3 4
hyper372@hyper372-test:~/Documents/grpc/examples/cpp/helloworld/build$ ./greeter_callback_client WARNING: All log messages before absl::InitializeLog() is called are written to STDERR I0000 00:00:1723773123.258449 4604 config.cc:257] gRPC experiments enabled: call_status_override_on_cancellation, call_tracer_in_transport, event_engine_dns, event_engine_listener, monitoring_experiment, pick_first_new, trace_record_callops, work_serializer_clears_time_cache Greeter received: Hello world