GRPC Objective-C Quickstart

为什么使用GRPC?

  • Google出品,基于HTTP2.0,减少TCP握手次数,客户端快,省电,服务端并发。需要Protobuf3.0配合使用。

iOS 如何使用?

  • 在工程目录添加一个后缀名为 .podspec的文件, HelloWorld.podspec文件内容见文档(.podspec 制作私有库时也需要这个文件,主要是和CocoaPods关联)
  • CocoaPods

步骤

  1. CocoaPods: version 1.0 or higher
  2. Xcode: version 7.2 or higher
  3. Homebrew
  4. brew install autoconf
    brew install automake brew upgrade automake
    brew install libtool
    brew install pkg-config brew upgrade pkg-config
  5. 下载示例程序
git clone --recursive -b v1.12.x https://github.com/grpc/grpc.git

grpc-github

  1. 下载插件和库
    git clone 之后默认下载到/User/yourAccountName目录下
cd /Users/“yourAccountName”/grpc/
make
sudo make install
  1. 安装protoc编译器
brew tap grpc/grpc
brew install protobuf
  1. Run the server
cd /Users/***/grpc/examples/cpp/helloworld/
make
./greeter_server &

make 之后会报错

protoc -I ../../protos --cpp_out=. ../../protos/helloworld.proto
g++ -std=c++11 `pkg-config --cflags protobuf grpc`  -c -o helloworld.pb.o helloworld.pb.cc
In file included from helloworld.pb.cc:5:
./helloworld.pb.h:9:10: fatal error: 'google/protobuf/stubs/common.h' file not found
#include <google/protobuf/stubs/common.h>
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
make: *** [helloworld.pb.o] Error 1

看到错误是不是很尴尬,这个原因是当前项目没有引入gRPC相关库。

所以,只要用pod 导入相关库即可。

  • 切换到工程目录
cd /Users/***/grpc/examples/objective-c/helloworld 
pod init
pod install
... wait install...
Analyzing dependencies
Fetching podspec for `HelloWorld` from `.`
Downloading dependencies
Installing !ProtoCompiler (3.5.0)
Installing !ProtoCompiler-gRPCPlugin (1.9.0)
Installing BoringSSL (9.2)
Installing HelloWorld (0.0.1)
Installing Protobuf (3.5.0)
Installing gRPC (1.9.0)
Installing gRPC-Core (1.9.0)
Installing gRPC-ProtoRPC (1.9.0)
Installing gRPC-RxLibrary (1.9.0)
Installing nanopb (0.3.8)
Generating Pods project
Integrating client project

[!] Please close any current Xcode sessions and use `HelloWorld.xcworkspace` for this project from now on.
Sending stats
Pod installation complete! There is 1 dependency from the Podfile and 10 total pods installed.

GRPC Objective-C Quickstart官方网站

.podspec官方网站

.podspec 文件

 # Base directory where the .proto files are. 根据注释可以知道这里是.proto文件的目录,如果就在工程目录的第一级文件夹下,直接写文件夹名字就可以。
 src = "protos"

# Run protoc with the Objective-C and gRPC plugins to generate protocol messages and gRPC clients.
 # You can run this command manually if you later change your protos and need to regenerate.  
 s.prepare_command = <<-CMD
   #{protoc} \
       --plugin=protoc-gen-grpc=#{plugin} \
       --objc_out=. \
       --grpc_out=. \
       -I . \
       -I #{protoc_dir} \
       google/*/*.proto google/*/*/*/*.proto 
最后一行是填写.proto文件的路径,
1. google为存放.proto的文件夹,
2. 如果google文件夹中存在多级文件目录,google/*/*.proto
3. 如果google文件夹中存在N级文件目录,googleN+1个/*.proto
N=3   google/*/*/*/*.proto 
两级目录.png

五级目录.png
scrforProto.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。