English

windows下 C++使用 grpc 详解

7/1/2024
33

这篇文章介绍如何在 windows 下使用C++ 操作 grpc 库。 linux 下 使用 grpc 比windows 简单很多,后面再出一篇文章 《在linux下 C++ 使用grpc》使用cmake 管理grpc 依赖。

项目代码仓库:

https://github.com/haydenzhourepo/windows-grpc_test_route_guide

安装 gRPC 和 Protocol Buffers

要使用gRPC 库, 首先需要安装它,
这里介绍2种安装方式,1. 源码编译,2. 使用 vcpkg 安装

1. 源码编译

1)首先使用 git 克隆 grpc 仓库到本地, 然后下载 submodule 中的依赖代码。 这里使用 v1.15.1 版本, 当前最新的版本是1.65.0测试了一下windows 下 有bug -_-|| .

Bash
git clone -b v1.51.1 https://github.com/grpc/grpc
cd grpc
git submodule update --init

2)使用cmake 编译

查看当前平台支持的generator, 前面标记了标记了 * 的是cmake 默认使用的generator。

可以看到当前 cmake 默认使用的 generator 是 Visual Studio 17 2022

Bash
$ cmake --help

windows下 C++使用 grpc 详解

配置项目并生成原生构建系统, 这里 通过 -DCMAKE_PREFIX_PATH 指定了安装目录为~/soft/grpc1_51,  grpc1_51 表示这是v1.51 版本的grpc 构建产物, 我们不建议直接将grpc安装到系统目录下。可能以后我们需要安装别的版本 只需要在建一个目录就行, 方便多版本管理。

Bash
// 创建.build 目录
mkdir .build
cd .build


$ cmake -DgRPC_INSTALL=ON -DCMAKE_INSTALL_PREFIX=~/soft/grpc1_51  ..

-- Building for: Visual Studio 17 2022
-- Selecting Windows SDK version 10.0.22621.0 to target Windows 10.0.22631.
-- The C compiler identification is MSVC 19.39.33523.0
-- The CXX compiler identification is MSVC 19.39.33523.0
-- Detecting C compiler ABI info
.....

因为我本地默认的 generator 是 Visual Studio 17 2022 所以我可以不用制定 generator
也可以通过 -G 手动指定 generator 

编译

Bash
cmake --build . --config Release

编译完成后 执行安装命令, 就将grpc 安装到 之前制定的目录 ~/soft/grpc1_51

Bash
cmake --install . 
windows下 C++使用 grpc 详解

在这个目录中,有3个子目录比较重要分别是:
* bin 目录存放这一些可执行文件,比如 protoc.exe 后面我们需要用来编译protobuf 文件, grpc_cpp_plugin.exe 插件 用来生成grpc 的代码。
* inlcude 目录包含了后面项目需要 include 头文件。

* lib 目录包含了后面项目需要 链接的 静态库。

我们可以将bin 目录添加到windows 系统环境变量中 , 这里为了简单起见,我直接用export 命令临时向当前bash 会话添加环境变量

Bash
# export environment variable
export PATH=$PATH:~/soft/grpc1_51/bin

2. 使用 vcpkg 安装

1)首先安装 vcpkg, 安装完成后继续安装 grpc。 安装grpc动态库比较容易,所以这里我们以 64位静态库为例演示。

Tips:  可以去triplets 目录下查看 支持哪些 triplets

windows下 C++使用 grpc 详解
Bash
 ./vcpkg install grpc --triplet=x64-windows-static

2)安装完成后 使用 list 命令查看一下:

Bash
./vcpkg list --triplet=x64-windows-static



c-ares:x64-windows                                1.28.1              A C library for asynchronous DNS requests
c-ares:x64-windows-static                         1.28.1              A C library for asynchronous DNS requests
c-ares:x86-windows                                1.28.1              A C library for asynchronous DNS requests
grpc:x64-windows                                  1.51.1#3            gRPC is a modern, open source, high-performance ...
grpc:x64-windows-static                           1.51.1#3            gRPC is a modern, open source, high-performance ...
grpc[codegen]:x64-windows                                             Build code generator machinery
openssl:x64-windows                               3.3.0#1             OpenSSL is an open source project that provides ...
openssl:x64-windows-static                        3.3.0#1             OpenSSL is an open source project that provides ...
openssl:x86-windows                               3.3.0#1             OpenSSL is an open source project that provides ...
protobuf:x64-windows                              3.21.12#3           Google's language-neutral, platform-neutral, ext...
protobuf:x64-windows-static                       3.21.12#3           Google's language-neutral, platform-neutral, ext...
protobuf:x86-windows                              3.21.12#3           Google's language-neutral, platform-neutral, ext...
re2:x64-windows                                   2024-04-01#2        RE2 is a fast, safe, thread-friendly alternative...
re2:x64-windows-static                            2024-04-01#2        RE2 is a fast, safe, thread-friendly alternative...
re2:x86-windows                                   2024-04-01#2        RE2 is a fast, safe, thread-friendly altern

3)查看vcpkg 的目录结构

vcpkg 将 grpc 安装到了 installed/x64-windows-static 目录下。

windows下 C++使用 grpc 详解

与源码编译安装不一样的是 vcpkg 将打包的 可执行文件 放到了 tools 目录中, 而且是 没有安装到 x64-windows-static triplet 下面, 应该是个bug。不过不影响使用

windows下 C++使用 grpc 详解

grpc 的头文件 和 库文件 还是必须要用  x64-windows-static triplet 下面的

windows下 C++使用 grpc 详解

4)接着让 IDE 集成 vcpkg

Bash
vcpkg integrate install 

下面以官方demo为例介绍如何在Visual studio中使用

1)首先创建一个 空解决方案 grpc_test_route_guide

windows下 C++使用 grpc 详解

2) 创建一个C++ 控制台项目 route_server

windows下 C++使用 grpc 详解

3) 接着创建一个 控制台项目 route_client

windows下 C++使用 grpc 详解

4) 定义 route_guide.proto 服务

windows下 C++使用 grpc 详解
C++
// route_guide.proto
syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.routeguide";
option java_outer_classname = "RouteGuideProto";
option objc_class_prefix = "RTG";

package routeguide;

// Interface exported by the server.
service RouteGuide {
  // A simple RPC.
  //
  // Obtains the feature at a given position.
  //
  // A feature with an empty name is returned if there's no feature at the given
  // position.
  rpc GetFeature(Point) returns (Feature) {}

  // A server-to-client streaming RPC.
  //
  // Obtains the Features available within the given Rectangle.  Results are
  // streamed rather than returned at once (e.g. in a response message with a
  // repeated field), as the rectangle may cover a large area and contain a
  // huge number of features.
  rpc ListFeatures(Rectangle) returns (stream Feature) {}

  // A client-to-server streaming RPC.
  //
  // Accepts a stream of Points on a route being traversed, returning a
  // RouteSummary when traversal is completed.
  rpc RecordRoute(stream Point) returns (RouteSummary) {}

  // A Bidirectional streaming RPC.
  //
  // Accepts a stream of RouteNotes sent while a route is being traversed,
  // while receiving other RouteNotes (e.g. from other users).
  rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
}

// Points are represented as latitude-longitude pairs in the E7 representation
// (degrees multiplied by 10**7 and rounded to the nearest integer).
// Latitudes should be in the range +/- 90 degrees and longitude should be in
// the range +/- 180 degrees (inclusive).
message Point {
  int32 latitude = 1;
  int32 longitude = 2;
}

// A latitude-longitude rectangle, represented as two diagonally opposite
// points "lo" and "hi".
message Rectangle {
  // One corner of the rectangle.
  Point lo = 1;

  // The other corner of the rectangle.
  Point hi = 2;
}

// A feature names something at a given point.
//
// If a feature could not be named, the name is empty.
message Feature {
  // The name of the feature.
  string name = 1;

  // The point where the feature is detected.
  Point location = 2;
}

// A RouteNote is a message sent while at a given point.
message RouteNote {
  // The location from which the message is sent.
  Point location = 1;

  // The message to be sent.
  string message = 2;
}

// A RouteSummary is received in response to a RecordRoute rpc.
//
// It contains the number of individual points received, the number of
// detected features, and the total distance covered as the cumulative sum of
// the distance between each point.
message RouteSummary {
  // The number of points received.
  int32 point_count = 1;

  // The number of known features passed while traversing the route.
  int32 feature_count = 2;

  // The distance covered in metres.
  int32 distance = 3;

  // The duration of the traversal in seconds.
  int32 elapsed_time = 4;
}

可以看到我们定义使用的 protobuf 协议版本是3

定义了 RouteGuide 服务,这个服务有 4 个方法,对应grpc 支持的 4 种类接口。

C++
// 简单 RPC. 
rpc GetFeature(Point) returns (Feature) {}

 // 服务端向客户端的流 RPC.
 rpc ListFeatures(Rectangle) returns (stream Feature) {}

 // 客户端向服务端的流 RPC.
 rpc RecordRoute(stream Point) returns (RouteSummary) {}

 // 双向流 RPC.
 rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}

另外也定义了 消息格式

C++
message Point {
  int32 latitude = 1;
  int32 longitude = 2;
}

message Rectangle {
  Point lo = 1;
  Point hi = 2;
}

message Feature {
  string name = 1;
  Point location = 2;
}

message RouteNote {
  Point location = 1;
  string message = 2;
}

message RouteSummary {
  int32 point_count = 1;
  int32 feature_count = 2;
  int32 distance = 3;
  int32 elapsed_time = 4;
}

至于 protobuf 语言的格式可以参考: https://protobuf.dev/programming-guides/proto3/

5)编译 grpc 服务端和客户端通信桩代码,以及消息序列化代码

C++
# build from source
## export environment variable
export PATH=$PATH:~/soft/grpc1_51/bin

## generate grpc server and client stub code
protoc.exe --grpc_out=./proto --plugin=protoc-gen-grpc=/c/Users/mfkha/soft/grpc1_51/bin/grpc_cpp_plugin.exe route_guide.proto

## generate grpc message serialisable code
protoc.exe --cpp_out=./proto route_guide.proto

 --grpc_out  生成 grpc 框架代码,  --cpp_out 生成 grpc 消息序列号代码, 如果只需要序列号 消息,则可以不用 执行 --grpc_out 

6)编写 route_server 代码

首先添加include 和 lib 依赖 目录

windows下 C++使用 grpc 详解
windows下 C++使用 grpc 详解

使用命令列出 所有的grpc lib, 添加项目依赖

windows下 C++使用 grpc 详解
windows下 C++使用 grpc 详解

将 所有的依赖添加完毕后, 再 添加一个 crypt32.lib 原因是 windows 下 openssl 需要 额外的这个库。参考:https://github.com/openssl/openssl/issues/1061

添加完成后。就可以完成 server 的代码了

C++
#include <random>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <memory>
#include <string>
#include <fstream>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <vector>

#include <grpc/grpc.h>
#include <grpcpp/security/server_credentials.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "route_guide.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;
using routeguide::Feature;
using routeguide::Point;
using routeguide::Rectangle;
using routeguide::RouteGuide;
using routeguide::RouteNote;
using routeguide::RouteSummary;
using std::chrono::system_clock;


namespace routeguide {
    std::string GetDbFileContent(int argc, char** argv) {
        std::string db_path;
        std::string arg_str("--db_path");
        if (argc > 1) {
            std::string argv_1 = argv[1];
            size_t start_position = argv_1.find(arg_str);
            if (start_position != std::string::npos) {
                start_position += arg_str.size();
                if (argv_1[start_position] == ' ' || argv_1[start_position] == '=') {
                    db_path = argv_1.substr(start_position + 1);
                }
            }
        }
        else {
#ifdef BAZEL_BUILD
            db_path = "cpp/route_guide/route_guide_db.json";
#else
            db_path = "route_guide_db.json";
#endif
        }
        std::ifstream db_file(db_path);
        if (!db_file.is_open()) {
            std::cout << "Failed to open " << db_path << std::endl;
            abort();
        }
        std::stringstream db;
        db << db_file.rdbuf();
        return db.str();
    }

    // A simple parser for the json db file. It requires the db file to have the
    // exact form of [{"location": { "latitude": 123, "longitude": 456}, "name":
    // "the name can be empty" }, { ... } ... The spaces will be stripped.
    class Parser {
    public:
        explicit Parser(const std::string& db) : db_(db) {
            // Remove all spaces.
            db_.erase(std::remove_if(db_.begin(), db_.end(), isspace), db_.end());
            if (!Match("[")) {
                SetFailedAndReturnFalse();
            }
        }

        bool Finished() { return current_ >= db_.size(); }

        bool TryParseOne(Feature* feature) {
            if (failed_ || Finished() || !Match("{")) {
                return SetFailedAndReturnFalse();
            }
            if (!Match(location_) || !Match("{") || !Match(latitude_)) {
                return SetFailedAndReturnFalse();
            }
            long temp = 0;
            ReadLong(&temp);
            feature->mutable_location()->set_latitude(temp);
            if (!Match(",") || !Match(longitude_)) {
                return SetFailedAndReturnFalse();
            }
            ReadLong(&temp);
            feature->mutable_location()->set_longitude(temp);
            if (!Match("},") || !Match(name_) || !Match("\"")) {
                return SetFailedAndReturnFalse();
            }
            size_t name_start = current_;
            while (current_ != db_.size() && db_[current_++] != '"') {
            }
            if (current_ == db_.size()) {
                return SetFailedAndReturnFalse();
            }
            feature->set_name(db_.substr(name_start, current_ - name_start - 1));
            if (!Match("},")) {
                if (db_[current_ - 1] == ']' && current_ == db_.size()) {
                    return true;
                }
                return SetFailedAndReturnFalse();
            }
            return true;
        }

    private:
        bool SetFailedAndReturnFalse() {
            failed_ = true;
            return false;
        }

        bool Match(const std::string& prefix) {
            bool eq = db_.substr(current_, prefix.size()) == prefix;
            current_ += prefix.size();
            return eq;
        }

        void ReadLong(long* l) {
            size_t start = current_;
            while (current_ != db_.size() && db_[current_] != ',' &&
                db_[current_] != '}') {
                current_++;
            }
            // It will throw an exception if fails.
            *l = std::stol(db_.substr(start, current_ - start));
        }

        bool failed_ = false;
        std::string db_;
        size_t current_ = 0;
        const std::string location_ = "\"location\":";
        const std::string latitude_ = "\"latitude\":";
        const std::string longitude_ = "\"longitude\":";
        const std::string name_ = "\"name\":";
    };

    void ParseDb(const std::string& db, std::vector<Feature>* feature_list) {
        feature_list->clear();
        std::string db_content(db);
        db_content.erase(
            std::remove_if(db_content.begin(), db_content.end(), isspace),
            db_content.end());

        Parser parser(db_content);
        Feature feature;
        while (!parser.Finished()) {
            feature_list->push_back(Feature());
            if (!parser.TryParseOne(&feature_list->back())) {
                std::cout << "Error parsing the db file";
                feature_list->clear();
                break;
            }
        }
        std::cout << "DB parsed, loaded " << feature_list->size() << " features."
            << std::endl;
    }
}

float ConvertToRadians(float num) { return num * 3.1415926 / 180; }

// The formula is based on http://mathforum.org/library/drmath/view/51879.html
float GetDistance(const Point& start, const Point& end) {
    const float kCoordFactor = 10000000.0;
    float lat_1 = start.latitude() / kCoordFactor;
    float lat_2 = end.latitude() / kCoordFactor;
    float lon_1 = start.longitude() / kCoordFactor;
    float lon_2 = end.longitude() / kCoordFactor;
    float lat_rad_1 = ConvertToRadians(lat_1);
    float lat_rad_2 = ConvertToRadians(lat_2);
    float delta_lat_rad = ConvertToRadians(lat_2 - lat_1);
    float delta_lon_rad = ConvertToRadians(lon_2 - lon_1);

    float a = pow(sin(delta_lat_rad / 2), 2) +
        cos(lat_rad_1) * cos(lat_rad_2) * pow(sin(delta_lon_rad / 2), 2);
    float c = 2 * atan2(sqrt(a), sqrt(1 - a));
    int R = 6371000;  // metres

    return R * c;
}

std::string GetFeatureName(const Point& point,
    const std::vector<Feature>& feature_list) {
    for (const Feature& f : feature_list) {
        if (f.location().latitude() == point.latitude() &&
            f.location().longitude() == point.longitude()) {
            return f.name();
        }
    }
    return "";
}

class RouteGuideImpl final : public RouteGuide::Service {
public:
    explicit RouteGuideImpl(const std::string& db) {
        routeguide::ParseDb(db, &feature_list_);
    }

    Status GetFeature(ServerContext* context, const Point* point,
        Feature* feature) override {
        feature->set_name(GetFeatureName(*point, feature_list_));
        feature->mutable_location()->CopyFrom(*point);
        return Status::OK;
    }

    Status ListFeatures(ServerContext* context,
        const routeguide::Rectangle* rectangle,
        ServerWriter<Feature>* writer) override {
        auto lo = rectangle->lo();
        auto hi = rectangle->hi();
        long left = (std::min)(lo.longitude(), hi.longitude());
        long right = (std::max)(lo.longitude(), hi.longitude());
        long top = (std::max)(lo.latitude(), hi.latitude());
        long bottom = (std::min)(lo.latitude(), hi.latitude());
        for (const Feature& f : feature_list_) {
            if (f.location().longitude() >= left &&
                f.location().longitude() <= right &&
                f.location().latitude() >= bottom && f.location().latitude() <= top) {
                writer->Write(f);
            }
        }
        return Status::OK;
    }

    Status RecordRoute(ServerContext* context, ServerReader<Point>* reader,
        RouteSummary* summary) override {
        Point point;
        int point_count = 0;
        int feature_count = 0;
        float distance = 0.0;
        Point previous;

        system_clock::time_point start_time = system_clock::now();
        while (reader->Read(&point)) {
            point_count++;
            if (!GetFeatureName(point, feature_list_).empty()) {
                feature_count++;
            }
            if (point_count != 1) {
                distance += GetDistance(previous, point);
            }
            previous = point;
        }
        system_clock::time_point end_time = system_clock::now();
        summary->set_point_count(point_count);
        summary->set_feature_count(feature_count);
        summary->set_distance(static_cast<long>(distance));
        auto secs =
            std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time);
        summary->set_elapsed_time(secs.count());

        return Status::OK;
    }

    Status RouteChat(ServerContext* context,
        ServerReaderWriter<RouteNote, RouteNote>* stream) override {
        RouteNote note;
        while (stream->Read(&note)) {
            std::unique_lock<std::mutex> lock(mu_);
            for (const RouteNote& n : received_notes_) {
                if (n.location().latitude() == note.location().latitude() &&
                    n.location().longitude() == note.location().longitude()) {
                    stream->Write(n);
                }
            }
            received_notes_.push_back(note);
        }

        return Status::OK;
    }

private:
    std::vector<Feature> feature_list_;
    std::mutex mu_;
    std::vector<RouteNote> received_notes_;
};

void RunServer(const std::string& db_path) {
    std::string server_address("0.0.0.0:50051");
    RouteGuideImpl service(db_path);

    ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    builder.RegisterService(&service);
    std::unique_ptr<Server> server(builder.BuildAndStart());
    std::cout << "Server listening on " << server_address << std::endl;
    server->Wait();
}

int main(int argc, char** argv) {
    // Expect only arg: --db_path=path/to/route_guide_db.json.
    std::string db = routeguide::GetDbFileContent(argc, argv);
    RunServer(db);

    return 0;
}

最后 我们 将 protoc.exe 生成的 *.cc 源文件 全部添加到项目中

windows下 C++使用 grpc 详解

编译server 就行了,

7)接下来 按照 server 同样的 方式, 实现 route_client

首先添加include 和 lib 依赖 目录,  然后添加所有的依赖项。

最后添加 route_client.cpp

C++
/*
 *
 * 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.
 *
 */

#include <chrono>
#include <iostream>
#include <memory>
#include <random>
#include <string>
#include <thread>
#include <fstream>
#include <sstream>


#include <grpc/grpc.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#ifdef BAZEL_BUILD
#include "examples/protos/route_guide.grpc.pb.h"
#else
#include "route_guide.grpc.pb.h"
#endif


namespace routeguide {

    std::string GetDbFileContent(int argc, char** argv) {
        std::string db_path;
        std::string arg_str("--db_path");
        if (argc > 1) {
            std::string argv_1 = argv[1];
            size_t start_position = argv_1.find(arg_str);
            if (start_position != std::string::npos) {
                start_position += arg_str.size();
                if (argv_1[start_position] == ' ' || argv_1[start_position] == '=') {
                    db_path = argv_1.substr(start_position + 1);
                }
            }
        }
        else {
#ifdef BAZEL_BUILD
            db_path = "cpp/route_guide/route_guide_db.json";
#else
            db_path = "route_guide_db.json";
#endif
        }
        std::ifstream db_file(db_path);
        if (!db_file.is_open()) {
            std::cout << "Failed to open " << db_path << std::endl;
            abort();
        }
        std::stringstream db;
        db << db_file.rdbuf();
        return db.str();
    }

    // A simple parser for the json db file. It requires the db file to have the
    // exact form of [{"location": { "latitude": 123, "longitude": 456}, "name":
    // "the name can be empty" }, { ... } ... The spaces will be stripped.
    class Parser {
    public:
        explicit Parser(const std::string& db) : db_(db) {
            // Remove all spaces.
            db_.erase(std::remove_if(db_.begin(), db_.end(), isspace), db_.end());
            if (!Match("[")) {
                SetFailedAndReturnFalse();
            }
        }

        bool Finished() { return current_ >= db_.size(); }

        bool TryParseOne(Feature* feature) {
            if (failed_ || Finished() || !Match("{")) {
                return SetFailedAndReturnFalse();
            }
            if (!Match(location_) || !Match("{") || !Match(latitude_)) {
                return SetFailedAndReturnFalse();
            }
            long temp = 0;
            ReadLong(&temp);
            feature->mutable_location()->set_latitude(temp);
            if (!Match(",") || !Match(longitude_)) {
                return SetFailedAndReturnFalse();
            }
            ReadLong(&temp);
            feature->mutable_location()->set_longitude(temp);
            if (!Match("},") || !Match(name_) || !Match("\"")) {
                return SetFailedAndReturnFalse();
            }
            size_t name_start = current_;
            while (current_ != db_.size() && db_[current_++] != '"') {
            }
            if (current_ == db_.size()) {
                return SetFailedAndReturnFalse();
            }
            feature->set_name(db_.substr(name_start, current_ - name_start - 1));
            if (!Match("},")) {
                if (db_[current_ - 1] == ']' && current_ == db_.size()) {
                    return true;
                }
                return SetFailedAndReturnFalse();
            }
            return true;
        }

    private:
        bool SetFailedAndReturnFalse() {
            failed_ = true;
            return false;
        }

        bool Match(const std::string& prefix) {
            bool eq = db_.substr(current_, prefix.size()) == prefix;
            current_ += prefix.size();
            return eq;
        }

        void ReadLong(long* l) {
            size_t start = current_;
            while (current_ != db_.size() && db_[current_] != ',' &&
                db_[current_] != '}') {
                current_++;
            }
            // It will throw an exception if fails.
            *l = std::stol(db_.substr(start, current_ - start));
        }

        bool failed_ = false;
        std::string db_;
        size_t current_ = 0;
        const std::string location_ = "\"location\":";
        const std::string latitude_ = "\"latitude\":";
        const std::string longitude_ = "\"longitude\":";
        const std::string name_ = "\"name\":";
    };

    void ParseDb(const std::string& db, std::vector<Feature>* feature_list) {
        feature_list->clear();
        std::string db_content(db);
        db_content.erase(
            std::remove_if(db_content.begin(), db_content.end(), isspace),
            db_content.end());

        Parser parser(db_content);
        Feature feature;
        while (!parser.Finished()) {
            feature_list->push_back(Feature());
            if (!parser.TryParseOne(&feature_list->back())) {
                std::cout << "Error parsing the db file";
                feature_list->clear();
                break;
            }
        }
        std::cout << "DB parsed, loaded " << feature_list->size() << " features."
            << std::endl;
    }

}  

using grpc::Channel;
using grpc::ClientContext;
using grpc::ClientReader;
using grpc::ClientReaderWriter;
using grpc::ClientWriter;
using grpc::Status;
using routeguide::Feature;
using routeguide::Point;
using routeguide::Rectangle;
using routeguide::RouteGuide;
using routeguide::RouteNote;
using routeguide::RouteSummary;

Point MakePoint(long latitude, long longitude) {
    Point p;
    p.set_latitude(latitude);
    p.set_longitude(longitude);
    return p;
}

Feature MakeFeature(const std::string& name, long latitude, long longitude) {
    Feature f;
    f.set_name(name);
    f.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
    return f;
}

RouteNote MakeRouteNote(const std::string& message, long latitude,
    long longitude) {
    RouteNote n;
    n.set_message(message);
    n.mutable_location()->CopyFrom(MakePoint(latitude, longitude));
    return n;
}

class RouteGuideClient {
public:
    RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db)
        : stub_(RouteGuide::NewStub(channel)) {
        routeguide::ParseDb(db, &feature_list_);
    }

    void GetFeature() {
        Point point;
        Feature feature;
        point = MakePoint(409146138, -746188906);
        GetOneFeature(point, &feature);
        point = MakePoint(0, 0);
        GetOneFeature(point, &feature);
    }

    void ListFeatures() {
        routeguide::Rectangle rect;
        Feature feature;
        ClientContext context;

        rect.mutable_lo()->set_latitude(400000000);
        rect.mutable_lo()->set_longitude(-750000000);
        rect.mutable_hi()->set_latitude(420000000);
        rect.mutable_hi()->set_longitude(-730000000);
        std::cout << "Looking for features between 40, -75 and 42, -73"
            << std::endl;

        std::unique_ptr<ClientReader<Feature> > reader(
            stub_->ListFeatures(&context, rect));
        while (reader->Read(&feature)) {
            std::cout << "Found feature called " << feature.name() << " at "
                << feature.location().latitude() / kCoordFactor_ << ", "
                << feature.location().longitude() / kCoordFactor_ << std::endl;
        }
        Status status = reader->Finish();
        if (status.ok()) {
            std::cout << "ListFeatures rpc succeeded." << std::endl;
        }
        else {
            std::cout << "ListFeatures rpc failed." << std::endl;
        }
    }

    void RecordRoute() {
        Point point;
        RouteSummary stats;
        ClientContext context;
        const int kPoints = 10;
        unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

        std::default_random_engine generator(seed);
        std::uniform_int_distribution<int> feature_distribution(
            0, feature_list_.size() - 1);
        std::uniform_int_distribution<int> delay_distribution(500, 1500);

        std::unique_ptr<ClientWriter<Point> > writer(
            stub_->RecordRoute(&context, &stats));
        for (int i = 0; i < kPoints; i++) {
            const Feature& f = feature_list_[feature_distribution(generator)];
            std::cout << "Visiting point " << f.location().latitude() / kCoordFactor_
                << ", " << f.location().longitude() / kCoordFactor_
                << std::endl;
            if (!writer->Write(f.location())) {
                // Broken stream.
                break;
            }
            std::this_thread::sleep_for(
                std::chrono::milliseconds(delay_distribution(generator)));
        }
        writer->WritesDone();
        Status status = writer->Finish();
        if (status.ok()) {
            std::cout << "Finished trip with " << stats.point_count() << " points\n"
                << "Passed " << stats.feature_count() << " features\n"
                << "Travelled " << stats.distance() << " meters\n"
                << "It took " << stats.elapsed_time() << " seconds"
                << std::endl;
        }
        else {
            std::cout << "RecordRoute rpc failed." << std::endl;
        }
    }

    void RouteChat() {
        ClientContext context;

        std::shared_ptr<ClientReaderWriter<RouteNote, RouteNote> > stream(
            stub_->RouteChat(&context));

        std::thread writer([stream]() {
            std::vector<RouteNote> notes{ MakeRouteNote("First message", 0, 0),
                                         MakeRouteNote("Second message", 0, 1),
                                         MakeRouteNote("Third message", 1, 0),
                                         MakeRouteNote("Fourth message", 0, 0) };
        for (const RouteNote& note : notes) {
            std::cout << "Sending message " << note.message() << " at "
                << note.location().latitude() << ", "
                << note.location().longitude() << std::endl;
            stream->Write(note);
        }
        stream->WritesDone();
            });

        RouteNote server_note;
        while (stream->Read(&server_note)) {
            std::cout << "Got message " << server_note.message() << " at "
                << server_note.location().latitude() << ", "
                << server_note.location().longitude() << std::endl;
        }
        writer.join();
        Status status = stream->Finish();
        if (!status.ok()) {
            std::cout << "RouteChat rpc failed." << std::endl;
        }
    }

private:
    bool GetOneFeature(const Point& point, Feature* feature) {
        ClientContext context;
        Status status = stub_->GetFeature(&context, point, feature);
        if (!status.ok()) {
            std::cout << "GetFeature rpc failed." << std::endl;
            return false;
        }
        if (!feature->has_location()) {
            std::cout << "Server returns incomplete feature." << std::endl;
            return false;
        }
        if (feature->name().empty()) {
            std::cout << "Found no feature at "
                << feature->location().latitude() / kCoordFactor_ << ", "
                << feature->location().longitude() / kCoordFactor_ << std::endl;
        }
        else {
            std::cout << "Found feature called " << feature->name() << " at "
                << feature->location().latitude() / kCoordFactor_ << ", "
                << feature->location().longitude() / kCoordFactor_ << std::endl;
        }
        return true;
    }

    const float kCoordFactor_ = 10000000.0;
    std::unique_ptr<RouteGuide::Stub> stub_;
    std::vector<Feature> feature_list_;
};

int main(int argc, char** argv) {
    // Expect only arg: --db_path=path/to/route_guide_db.json.
    std::string db = routeguide::GetDbFileContent(argc, argv);
    RouteGuideClient guide(
        grpc::CreateChannel("localhost:50051",
            grpc::InsecureChannelCredentials()),
        db);

    std::cout << "-------------- GetFeature --------------" << std::endl;
    guide.GetFeature();
    std::cout << "-------------- ListFeatures --------------" << std::endl;
    guide.ListFeatures();
    std::cout << "-------------- RecordRoute --------------" << std::endl;
    guide.RecordRoute();
    std::cout << "-------------- RouteChat --------------" << std::endl;
    guide.RouteChat();

    return 0;
}
windows下 C++使用 grpc 详解

编译route_client

8) 运行测试

编译完成 server 和 client 项目后, 在项目的 x64/Release 目录下面生成了 route_server.exe 与 route_client.exe 2 个可执行文件。 分别运行 这 2个可执行文件 就可以测试了。 测试结果都正常运行。

windows下 C++使用 grpc 详解
windows下 C++使用 grpc 详解
windows下 C++使用 grpc 详解

2 Visual studio 使用 VCPKG 依赖。

编译 grpc 服务端和客户端通信桩代码,以及消息序列化代码

Bash
// gen.sh

# installed by vcpkg
## export environment variable
export PATH=$PATH:~/soft/vcpkg/installed/x64-windows/tools/grpc
export PATH=$PATH:~/soft/vcpkg/installed/x64-windows/tools/protobuf

## generate grpc server and client stub code
protoc.exe --grpc_out=./proto --plugin=protoc-gen-grpc=/c/Users/mfkha/soft/vcpkg/installed/x64-windows/tools/grpc/grpc_cpp_plugin.exe route_guide.proto

## generate grpc message serialisable code
protoc.exe --cpp_out=./proto route_guide.proto

1)配置 route_server

使用 vcpkg 来管理依赖就比较简单了。 vcpkg 可以自动链接 需要的依赖,所以 我们可以去掉 项目配置中的 添加依赖的 部分

windows下 C++使用 grpc 详解

除了 crypt32.lib 其他的全部删除掉。

windows下 C++使用 grpc 详解

删掉 include 目录

windows下 C++使用 grpc 详解

删掉 lib 目录

windows下 C++使用 grpc 详解

配置 vcpkg 使用 静态库, triplet 设置为x64-windows-static

windows下 C++使用 grpc 详解

修改 Runtime Library 为 Multi-threaded(/MT)

完成后 编译一下:

windows下 C++使用 grpc 详解

编译成功

2) 配置route_client

使用同 route_server 一样的方式 来修改项目配置 然后编译

windows下 C++使用 grpc 详解

3)server 和 client 都编译成功后, 同样的我们开始测试

windows下 C++使用 grpc 详解

由于依赖都是静态链接的所以这里没有别的 dll。

如果是 动态链接的话, 编译完成后 在 Release 目录下会多出额外的 可执行文件需要的 动态链接库

windows下 C++使用 grpc 详解

最后我们同样跑一下 server 和 client

windows下 C++使用 grpc 详解
windows下 C++使用 grpc 详解

可以看到都能正常的运行。

可以看到 使用vcpkg 管理依赖简单很多。所以这里也推荐大家多使用vcpkg。

https://vcpkg.io/