写一个使用JSON作为序列化协议的gRPC通信的客户端和服务端
时间: 2024-02-23 16:59:27 浏览: 68
下面是一个使用JSON作为序列化协议的gRPC通信的客户端和服务端的示例,其中定义了一个名为`HelloWorld`的简单服务,客户端发送一个名为`name`的字符串,服务端返回一个包含`Hello, name!`的字符串:
#### 服务端
```cpp
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "helloworld.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
class GreeterServiceImpl final : 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;
}
};
void RunServer() {
std::string server_address("0.0.0.0:50051");
GreeterServiceImpl service;
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
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(int argc, char** argv) {
RunServer();
return 0;
}
```
#### 客户端
```cpp
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/health_check_service_interface.h>
#include "helloworld.grpc.pb.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloReply;
using helloworld::Greeter;
class GreeterClient {
public:
GreeterClient(std::shared_ptr<Channel> channel)
: stub_(Greeter::NewStub(channel)) {}
std::string SayHello(const std::string& name) {
HelloRequest request;
request.set_name(name);
HelloReply reply;
ClientContext context;
std::string serializedRequest, serializedReply;
grpc::SerializationTraits<HelloRequest>::serialize(request, &serializedRequest);
Status status = stub_->CallRPC("SayHello", serializedRequest, &serializedReply);
if (status.ok()) {
grpc::SerializationTraits<HelloReply>::deserialize(serializedReply, &reply);
return reply.message();
} else {
std::cout << "RPC failed: " << status.error_message() << std::endl;
return "";
}
}
private:
std::unique_ptr<Greeter::Stub> stub_;
};
int main(int argc, char** argv) {
std::string name("World");
GreeterClient greeter(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));
std::string reply = greeter.SayHello(name);
std::cout << "Received: " << reply << std::endl;
return 0;
}
```
在这个例子中,我们使用了`grpc::SerializationTraits`类将请求和响应对象序列化为JSON字符串。`GreeterClient`类实现了客户端的逻辑,`SayHello`函数发送一个`HelloRequest`对象到服务端,并返回一个包含`Hello, name!`的字符串。在`main`函数中,我们使用`CreateChannel`函数创建一个与服务端通信的通道,并使用`GreeterClient`类进行通信。
阅读全文