gRPC是一个现代的、开源的、高性能远程过程调用(RPC)框架,可以在任何平台运行。gRPC使客户端和服务器端应用程序能够透明地进行通信,并简化了连接系统的构建。gRPC支持的语言包括C++、Ruby、Python、Java、Go等。

gRPC默认使用Google的Protocol Buffers,关于Protocol Buffers的介绍可以参考:https://blog.csdn.net/fengbingchun/article/details/49977903

gRPC的源码在https://github.com/grpc/grpc,最新版本的版本为v1.23.0,它的license是Apache-2.0。

关于RPC(Remote Procedure Call, 远程过程调用)的介绍可以参考:https://blog.csdn.net/fengbingchun/article/details/92406377

关于gRPC的安装可以参考:https://blog.csdn.net/fengbingchun/article/details/100608370

下面参考gRPC官方examples/cpp/helloworld中的同步模式例子,过程如下:

1. 创建IDL(interface definition language)描述文件helloworld.proto,通过protobuf定义服务端与客户端之间的RPC调用接口,通过protoc工具生成客户端和服务端代码。gRPC是需要先定义服务接口约定,才可以进行RPC调用,使用.proto可以同时定义客户端和服务端交换的数据格式以及RPC调用的接口。helloworld.proto文件内容如下:

// Copyright 2015 gRPC authors.syntax = "proto3";option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";package helloworld;// The greeting service definition.
service Greeter {// Sends a greetingrpc SayHello (HelloRequest) returns (HelloReply) {}
}// The request message containing the user's name.
message HelloRequest {string name = 1;
}// The response message containing the greetings
message HelloReply {string message = 1;
}

通过protoc工具生成服务端和客户端代码,执行命令(终端定位在demo/gRGC_Test)如下:

./../../src/grpc/linux_install/bin/protoc --cpp_out=./ helloworld.proto
./../../src/grpc/linux_install/bin/protoc --grpc_out=./ --plugin=protoc-gen-grpc=./../../src/grpc/linux_install/bin/grpc_cpp_plugin helloworld.proto

会在当前目录下生成helloworld.pb.h, hellowrold.pb.cc, helloworld.grpc.pb.h, helloworld.grpc.pb.cc四个文件。使用IDL定义服务端方法、参数、返回类型,客户端和服务端都使用从服务端定义生成的接口代码。

2. 编写客户端代码,测试代码函数为test_grpc_client;

3. 编写服务端代码,测试代码函数为test_grpc_server;

#include "funset.hpp"
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"// reference: grpc/examples/cpp/helloworld
namespace {class GreeterClient {
public:GreeterClient(std::shared_ptr<grpc::Channel> channel) : stub_(helloworld::Greeter::NewStub(channel)) {}// Assembles the client's payload, sends it and presents the response back from the server.std::string SayHello(const std::string& user) {// Data we are sending to the server.helloworld::HelloRequest request;request.set_name(user);// Container for the data we expect from the server.helloworld::HelloReply reply;// Context for the client. It could be used to convey extra information to the server and/or tweak certain RPC behaviors.grpc::ClientContext context;// The actual RPC.grpc::Status status = stub_->SayHello(&context, request, &reply);// Act upon its status.if (status.ok()) {return reply.message();} else {fprintf(stderr, "error code: %d, error message: %s\n", status.error_code(), status.error_message().c_str());return "RPC failed";}  }   private:std::unique_ptr<helloworld::Greeter::Stub> stub_;
};} // namespaceint test_grpc_client()
{fprintf(stdout, "client start\n");// Instantiate the client. It requires a channel, out of which the actual RPCs are created.// This channel models a connection to an endpoint (in this case, localhost at port 50051).// We indicate that the channel isn't authenticated(use of InsecureChannelCredentials()).GreeterClient greeter(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));std::string user("world");std::string reply = greeter.SayHello(user);fprintf(stdout, "Greeter received: %s\n", reply.c_str());return 0;
}namespace {// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public helloworld::Greeter::Service {grpc::Status SayHello(grpc::ServerContext* context, const helloworld::HelloRequest* request, helloworld::HelloReply* reply) override {std::string prefix("Hello ");reply->set_message(prefix + request->name());return grpc::Status::OK;}
};void RunServer() {std::string server_address("0.0.0.0:50051");GreeterServiceImpl service;grpc::ServerBuilder builder;// Listen on the given address without any authentication mechanism.builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());// Register "service" as the instance through which we'll communicate with clients.// In this case it corresponds to an *synchronous* service.builder.RegisterService(&service);// Finally assemble the server.std::unique_ptr<grpc::Server> server(builder.BuildAndStart());fprintf(stdout, "Server listening on: %s\n", server_address.c_str());// Wait for the server to shutdown. Note that some other thread must be// responsible for shutting down the server for this call to ever return.server->Wait();
}} // namespaceint test_grpc_server()
{fprintf(stdout, "server start\n");RunServer();return 0;
}

4. 先在一个终端启动服务端程序,再在另一个终端启动客户端程序,执行结果如下:

GitHub:https://github.com/fengbingchun/OpenSSL_Test

gRPC简介及简单使用(C++)相关推荐

  1. gRPC——简介与Hello World

    gRPC简介 gRPC 是一个高性能.开源.通用的RPC框架,由Google推出,基于HTTP2协议标准设计开发,默认采用Protocol Buffers数据序列化协议,支持多种开发语言.gRPC提供 ...

  2. gRPC in ASP.NET Core 3.x - gRPC 简介(2)

    前一篇: gRPC in ASP.NET Core 3.x - gRPC 简介(1) 身份认证 这里指的不是用户的身份认证,而是指多个server和client之间,它们如何识别出来谁是谁,并且能安全 ...

  3. gRPC(1)- gRPC 简介

    概述 在 gRPC 中,客户端应用程序可以直接调用不同机器上的服务器应用程序上的方法,就像它是本地对象一样,使您可以更轻松地创建分布式应用程序和服务.与许多 RPC 系统一样,gRPC 基于定义服务的 ...

  4. Spring AOP 简介以及简单用法

    Spring AOP 简介以及简单用法 如果你去面试java开发, 那么Spring的AOP和DI几乎是必问的问题. 那么AOP是什么呢? 一. AOP 所谓Aop就是 Aspect-Oriented ...

  5. 重要性采样(Importance Sampling)简介和简单样例实现

    重要性采样(Importance Sampling)简介和简单样例实现 在渲染领域,重要性采样这个术语是很常见的,但它究竟是什么呢?我们首先考虑这样的一种情况: 如果场景里有一点P,我们想计算P点的最 ...

  6. ONENET平台简介及简单的接入方法

    ONENET平台简介及简单的接入方法 OneNET是中国移动物联网有限公司响应"大众创新.万众创业"以及基于开放共赢的理念,面向公共服务自主研发的开放云平台,为各种跨平台物联网应用 ...

  7. knockout.js的简介和简单使用

    1.knockout简介 knockout是一个轻量级的UI类库,通过MVVM模式使JavaScript前端UI简单化 knockout有四大重要概念: 1)声明式绑定:使用简明移读的语法很容易地将模 ...

  8. dbus的代码范例 linux_Dbus简介与简单的收发示例程序

    Dbus简介与简单的收发示例程序. D-BUS 是一个大有前途的消息总线和活动系统,正开始深入地渗透到 Linux® 桌面之中.了解创建它的原因.它的用途以及发展前景. D-BUS 本质上是 进程间通 ...

  9. Grpc protoc的简单使用

    Grpc protoc的简单使用 Grpc:3.6.1  protoc:3.6.1  centos7.4 通过本篇文档可以了解protocol buffer内部的编解码机制,学习到如何源码编译安装,学 ...

最新文章

  1. 一台服务器两个mysql_在一台服务器上安装两个或多个mysql的实现步骤_MySQL
  2. Oracle中,如何查看FRA(Flashback Recovery Area)的利用率
  3. windows ping 不通虚拟机
  4. session多服务器共享的方案梳理
  5. 【python学习】——读取csv文件
  6. php 正则匹配收货地址,PHP简单实现正则匹配省市区的方法
  7. 现在70岁左右的人算不算是老年人?
  8. shell 脚本空行造成 :not found make.sh:
  9. 如何批量登陆远程主机和配置【转】
  10. Linux中常用查看日志命令
  11. 题目名称:你好,i春秋
  12. 【空气质量数据分析专题二】数据获取及预处理
  13. 云计算OpenStack环境搭建
  14. 8招教你将内容营销与SEO完美合一
  15. 陀螺仪的简单介绍讲解
  16. html5 主标题副标题,word如何设置正副标题
  17. 关于计算机缺少vcruntime140_1.dll的下载修复解决方案
  18. 如何使用ROS 控制桌面机械手Dobot魔术师?
  19. [012量化交易] python 最高价 最低价
  20. AE基础教程(14)——第14章 塌陷

热门文章

  1. Pytorch的神经网络编程学习第一节
  2. C++:随笔3--复杂的数据结构
  3. vector容器 begin()与end()函数、front()与back()的用法
  4. 设置VSCode打开键盘快捷方式和键盘快捷方式配置JSON分别快捷键为:Ctrl+Alt+K和Shift+Alt+K
  5. 如何安装“散装版”(如自己开发的)插件到VSCode
  6. Blender纹理基础学习视频教程 CGCookie – Fundamentals of Texturing in Blender
  7. Activity启动流程图
  8. 快速排序的实现与注意点
  9. 《UML大战需求分析》阅读笔记1
  10. Java中单元测试中:@BeforeClass,@Before,@Test,@After,@AfterClass中的问题详解