注1:参考代码取自 grpc 源码目录下的 examples\cpp\helloworld
注2:操作系统 Ubuntu 16.04
1. 安装 protoc 工具
- 下载 Grpc_v1.43.0_SetupFile.zip 文件,解压到任意目录
下载链接:https://pan.baidu.com/s/1HYjfQb8CQY56QF2iAGmBNw
提取码:grg0
注:Grpc_v1.43.0_SetupFile.zip 可由 grpc 源码编译安装得到,编译比较吃电脑配置,直接下载编译好的文件即可。
- 将解压后的 Grpc_v1.43.0_SetupFile/bin 中 的 protoc(文本文件,记录了版本信息)重命名为 protoc.version,然后将 protoc-3.18.1.0(可执行程序)拷贝一下并重命名为 protoc
注:原 protoc-3.18.1.0 文件也是需要用的,不能直接重命名。
- 在 Grpc_v1.43.0_SetupFile 目录打开终端,执行命令如下:
chmod +x bin/* sudo cp -r . /usr/local/
2. 通过 protoc 生成 c++ 代码
- 任意目录下新建空文件夹 grpc_cpp_demo,在文件夹中创建 helloworld.proto 文件,示例如下:View Code
// Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 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 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; }