---
title: "gRPC C++"
author: "tcspecial"
date: "2019-02-03T23:20:48Z"
tags: []
categories: ["开源软件"]
slug: "grpc-c"
draft: false
lastmod: "2019-02-04T14:34:18Z"
id: 2437365
url: "https://tcspecial.iteye.com/blog/2437365"
---

一. 准备编译环境

安装各种依赖库，详见：[Pre-requisites](https://github.com/grpc/grpc/blob/master/BUILDING.md)

```
brew install autoconf automake libtool shtool gflags
```

 

二. 安装protobuf3

```
git clone https://github.com/google/protobuf.git
cd protobuf
git checkout v3.5.0
sh ./autogen.sh
./configure --prefix=/usr/local/protobuf/  
make && make install
```

 

三. 安装grpc

```
git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc
cd grpc
git submodule update --init
make && make install 
```

 编译成功后会在/usr/local/bin/ 生成grpc各语言插件，如grpc\_cpp\_plugin，grpc\_php\_plugin等。

 

四. helloworld教程

详见：[gRPC C++ Hello World](https://github.com/grpc/grpc/tree/master/examples/cpp/helloworld)

 

4.1 编译proto

```
syntax = "proto3";

option java_package = "ex.grpc";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc 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;
}
```

 

4.2 生成stub

```
protoc --cpp_out=. helloworld.proto
protoc --grpc_out=. --plugin=protoc-gen-grpc=/usr/local/bin/grpc_cpp_plugin helloworld.proto 
```

 

4.3 编译运行

Makefile是通过pkg-config方式来查找protobuf, grpc库位置，可直接修改Makefile 指定protobuf, grpc库位置编译。

./greeter\_server

./greeter\_client 

客户端打印hello world

 

5\. 协议分析

grpc使用http2作为通信协议，http2使用多路复用，二进制帧进行数据传输，效率更高。

http2 报文详见：[RFC 7540 HTTP/2](https://www.rfc-editor.org/rfc/rfc7540.txt)

 

6.1 setting

每个stream固定9个字节头 + Payload，用于设置连接参数。

![setting frame](http://dl2.iteye.com/upload/attachment/0131/5062/29289fee-3352-3b12-8b9a-380f2d07ae5d.png)

 

 

 6.2 HEADERS

打开一个流，发起http请求。

http/1中的 method: POST\\r\\n，http2为len + :method + len + :post，且各头部字段均为小写。

![header frame](http://dl2.iteye.com/upload/attachment/0131/5060/5838e755-98ec-3f5b-86a4-918989145125.png)

 

 6.3 DATA

http1 header与data通过\\r\\n分隔，http2则为各个独立的stream。

![data frame](http://dl2.iteye.com/upload/attachment/0131/5058/65a673ef-3d75-331d-a210-a9ed120124bb.png)

 

 

 参考链接：

[grpc cpp demo](https://github.com/grpc/grpc/tree/master/examples/cpp/helloworld)

[http/2 详解](https://www.jianshu.com/p/e57ca4fec26f)