请确保已经安装了gRPC和Protobuf,并且已经生成了对应的RPC代码。在这个示例中,我们定义了一个HelloService,包含一个SayHello方法,该方法接收一个HelloRequest对象,并返回一个HelloResponse对象。服务端实现了这个服务,并在指定地址上监听。客户端创建一个HelloClient对象,并通过该对象调用远程方法。
1.服务端代码
#include <iostream>
#include <string>
#include <grpcpp/grpcpp.h>
#include "rpc_example.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using rpc_example::HelloRequest;
using rpc_example::HelloResponse;
using rpc_example::HelloService;
class HelloServiceImpl final : public HelloService::Service {
Status SayHello(ServerContext* context, const HelloRequest* request,
HelloResponse* response) override {
std::string prefix("Hello ");
response->set_message(prefix + request->name());
return Status::OK;
}
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
HelloServiceImpl service;
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
server->Wait();
}
int main() {
RunServer();
return 0;
}
2.客户端代码
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "rpc_example.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using rpc_example::HelloRequest;
using rpc_example::HelloResponse;
using rpc_example::HelloService;
class HelloClient {
public:
HelloClient(std::shared_ptr<Channel> channel)
: stub_(HelloService::NewStub(channel)) {}
std::string SayHello(const std::string& name) {
HelloRequest request;
request.set_name(name);
HelloResponse response;
ClientContext context;
Status status = stub_->SayHello(&context, request, &response);
if (status.ok()) {
return response.message();
} else {
std::cout << "RPC failed with error code: " << status.error_code()
<< ", error message: " << status.error_message() << std::endl;
return "RPC failed";
}
}
private:
std::unique_ptr<HelloService::Stub> stub_;
};
int main() {
std::string server_address("localhost:50051");
HelloClient client(grpc::CreateChannel(server_address, grpc::InsecureChannelCredentials()));
std::string name("Alice");
std::string response = client.SayHello(name);
std::cout << "Response: " << response << std::endl;
return 0;
}