在C++中,实现RPC(远程过程调用)通常涉及以下步骤:
以下是一个简单的示例,使用gRPC框架实现远程调用:
syntax = "proto3";
package helloworld;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
protoc
命令生成C++代码。#include <iostream>
#include <memory>
#include "helloworld.pb.h"
using namespace std;
using grpc::Server;
using grpc::ServerBuilder;
using helloworld::Greeter;
using helloworld::HelloRequest;
using helloworld::HelloReply;
class GreeterServiceImpl : public Greeter::Service {
public:
void SayHello(const HelloRequest* request, HelloReply* reply, ServerContext* context) override {
reply->set_message("Hello " + request->name());
}
};
int main(int argc, char** argv) {
ServerBuilder builder;
auto server = builder.AddListeningPort("localhost:50051", grpc::InsecureServerCredentials())
.AddService(new GreeterServiceImpl())
.Build();
server->Start();
server->Wait();
return 0;
}
#include <iostream>
#include <memory>
#include "helloworld.pb.h"
using namespace std;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloRequest;
using helloworld::HelloReply;
int main(int argc, char** argv) {
shared_ptr<GreeterClient> client(new GreeterClient("localhost:50051"));
HelloRequest request;
request.set_name("World");
HelloReply reply;
Status status = client->SayHello(&request, &reply);
if (status.ok()) {
cout << reply.message() << endl;
} else {
cout << "RPC failed: " << status.error_message() << endl;
}
return 0;
}
注意:这个示例使用了gRPC框架和Protocol Buffers,但你可以使用其他RPC框架(如Apache Thrift、RESTful API等)和序列化格式(如JSON、XML等)来实现类似的功能。