GRPC异步服务器和客户端

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 
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值