使用C++写一个grpc的通信案例
时间: 2023-07-18 12:07:06 浏览: 242
好的,以下是一个简单的grpc通信案例。
首先,安装protobuf和grpc。在Ubuntu下,可以使用以下命令安装:
```
sudo apt-get install protobuf-compiler
sudo apt-get install libprotobuf-dev
sudo apt-get install grpc-tools
sudo apt-get install libgrpc-dev
```
接下来,我们需要定义.proto文件。例如,我们定义一个Hello.proto文件:
```protobuf
syntax = "proto3";
package helloworld;
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
```
然后,使用以下命令生成C++代码:
```
protoc -I=./ --grpc_out=./ --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` ./Hello.proto
protoc -I=./ --cpp_out=./ ./Hello.proto
```
生成的代码包括Hello.pb.h和Hello.pb.cc,以及Hello.grpc.pb.h和Hello.grpc.pb.cc。
接下来,我们编写客户端代码:
```c++
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "Hello.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& user) {
HelloRequest request;
request.set_name(user);
HelloReply reply;
ClientContext context;
Status status = stub_->SayHello(&context, request, &reply);
if (status.ok()) {
return reply.message();
} else {
return "RPC failed";
}
}
private:
std::unique_ptr<Greeter::Stub> stub_;
};
int main(int argc, char** argv) {
GreeterClient greeter(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));
std::string user("world");
std::string reply = greeter.SayHello(user);
std::cout << "Greeter received: " << reply << std::endl;
return 0;
}
```
最后,编写服务器端代码:
```c++
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "Hello.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;
}
```
现在,我们可以先运行服务器端代码,然后再运行客户端代码,观察输出结果。
阅读全文