GRPC提拱了很多示例程序,可以访问下面的链接查阅:
CPP例子代码
编译PROTO文件
proto文件如下:
syntax = "proto3";
package helloworld;
option java_package = "com.pqtel.pqcloud.grpc";
option java_outer_classname = "helloworld";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloResponse) {
}
}
message HelloRequest {
string name = 1;
uint32 age = 2;
}
message HelloResponse {
string message = 1;
}
安装完protobuf以后,会生成一个protoc的执行程序:
protoc --grpc_out=. --plugin=protoc-gen-grpc=`which grpc_cpp_plugin` helloworld.proto
protoc --cpp_out=. helloworld.proto
执行完后会生成四个文件:
helloworld.grpc.pb.cc helloworld.grpc.pb.h helloworld.pb.cc helloworld.pb.h
服务器:
#include <memory>
#include <iostream>
#include <string>
#include <thread>
#include <grpcpp/grpcpp.h>
#include <grpc/support/log.h>
#include "helloworld.grpc.pb.h"
using grpc::Server;
using grpc::ServerAsyncResponseWriter;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerCompletionQueue;
using grpc::Status;
using helloworld::HelloRequest;
using helloworld::HelloResponse;
using helloworld::Greeter;
using namespace std;
class ServerImpl final {
public:
~ServerImpl() {
server_->Shutdown();
// 始终在服务之后关闭完成队列。
cq_->Shutdown();
}
// 此代码中没有关闭处理。
void Run()
{
string server_address("0.0.0.0:50051");
ServerBuilder builder;
/**************************************
************普通不加密通道*************
**************************************/
// 在没有任何认证机制的情况下监听给定地址。
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
// 注册 service_ 作为我们与客户沟通的实例。 在这种情况下,它对应于异步服务。
builder.RegisterService(&service_);
// 获取用于与gRPC运行时进行异步通信的完成队列。
cq_ = builder.AddCompletionQueue();
// 最后组装服务器。
server_ = builder.BuildAndStart();
cout << "Server listening on ----- " << server_address << endl << endl << endl;
// 继续进入服务器的主循环。
HandleRpcs();
}
private:
// 包含提供请求所需的状态和逻辑的类。
class