grpc记录(二)Windows下Qt使用grpc

1.编译grpc

参考:windows下使用Qt的MinGW编译grpc

2.配置环境变量

grpc编译完后,在C:\Program Files (x86)\grpc目录下有编译好的grpc的应用程序、库文件、头文件。复制地址C:\Program Files (x86)\grpc\bin,将此地址添加到环境变量。

打开cmd,输入protoc,回车,出现图中打印信息,表示配置成功。

protoc

3.写.proto文件,生成cpp文件

新建文件helloworld.proto,输入如下内容

syntax = "proto3";

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;
}

打开cmd,进入helloworld.proto文件所在目录,执行如下命令

protoc.exe ./helloworld.proto --cpp_out=./
protoc.exe ./helloworld.proto --plugin=protoc-gen-grpc=C:/Program Files (x86)/grpc/bin/grpc_cpp_plugin.exe --grpc_out=./

生成如下四个pb文件
helloworld.pb.h
helloworld.pb.cc
helloworld.grpc.pb.h
helloworld.grpc.pb.cc

4.客户端

在Qt中新建控制台程序GRpc_HelloWorld_Client,将pb文件添加到GRpc_HelloWorld_Client程序目录下

在这里插入图片描述
main.cpp

#include <QCoreApplication>

#include <iostream>
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "helloworld.grpc.pb.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

class GreeterClient {
 public:
  GreeterClient(std::shared_ptr<Channel> channel)
      : stub_(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.
    HelloRequest request;
    request.set_name(user);

    // Container for the data we expect from the server.
    HelloReply reply;

    // Context for the client. It could be used to convey extra information to
    // the server and/or tweak certain RPC behaviors.
    ClientContext context;

    // The actual RPC.
    Status status = stub_->SayHello(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {
      return reply.message();
    } else {
      std::cout << status.error_code() << ": " << status.error_message()
                << std::endl;
      return "RPC failed";
    }
  }

 private:
  std::unique_ptr<Greeter::Stub> stub_;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    GreeterClient greeter(
        grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));
    std::string user("world");
    std::string reply = greeter.SayHello(user);
    std::cout << "Greeter received: " << reply << std::endl;
    return a.exec();
}

5.服务端

在Qt中新建控制台程序GRpc_HelloWorld_Server,将pb文件添加到GRpc_HelloWorld_Server程序目录下

在这里插入图片描述
main.cpp

#include <QCoreApplication>
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>
#include "helloworld.grpc.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service {
  Status SayHello(ServerContext* context, const HelloRequest* request,
                  HelloReply* reply) override {
    std::string prefix("Hello ");
    reply->set_message(prefix + request->name());
    return Status::OK;
  }
};

void RunServer() {
  std::string server_address("0.0.0.0:50051");
  GreeterServiceImpl service;

  grpc::EnableDefaultHealthCheckService(true);
  grpc::reflection::InitProtoReflectionServerBuilderPlugin();
  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<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << std::endl;

  // 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();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    RunServer();
    return a.exec();
}

6.pro文件配置

GRpc_HelloWorld_Client.pro,GRpc_HelloWorld_Server.pro文件中添加如下内容

GRPC_HOME="C:/Program Files (x86)/grpc"

INCLUDEPATH += $$GRPC_HOME/include

LIBS += -L$$GRPC_HOME/lib -lgrpc++ -lgrpc -lgpr -lgrpc_plugin_support -lgrpc_unsecure -lgrpc++_alts \
-lgrpc++_error_details -lgrpc++_reflection -lgrpc++_unsecure -lgrpcpp_channelz -laddress_sorting \
-lcares -labsl_bad_any_cast_impl -labsl_bad_optional_access -labsl_bad_variant_access -labsl_civil_time \
-labsl_cordz_info -labsl_cord -labsl_cordz_functions -labsl_cordz_handle -labsl_cord_internal \
-labsl_cordz_sample_token -labsl_exponential_biased -labsl_flags -labsl_flags_commandlineflag \
-labsl_flags_commandlineflag_internal -labsl_flags_config -labsl_flags_internal -labsl_flags_marshalling \
-labsl_flags_parse -labsl_flags_private_handle_accessor -labsl_flags_program_name -labsl_flags_reflection \
-labsl_flags_usage -labsl_flags_usage_internal -labsl_synchronization -labsl_graphcycles_internal -labsl_hash \
-labsl_city -labsl_hashtablez_sampler -labsl_log_severity -labsl_low_level_hash -labsl_periodic_sampler \
-labsl_random_internal_pool_urbg -labsl_random_internal_seed_material -labsl_random_internal_randen_hwaes_impl \
-labsl_random_distributions -labsl_random_internal_distribution_test_util -labsl_random_internal_platform \
-labsl_random_internal_randen -labsl_random_internal_randen_hwaes -labsl_random_internal_randen_slow \
-labsl_random_seed_gen_exception -labsl_random_seed_sequences -labsl_raw_hash_set -labsl_scoped_set_env \
-labsl_spinlock_wait -labsl_status -labsl_statusor -labsl_str_format_internal -labsl_strerror -labsl_symbolize \
-labsl_failure_signal_handler -labsl_examine_stack -labsl_stacktrace -labsl_leak_check -labsl_leak_check_disable \
-labsl_debugging_internal -labsl_demangle_internal -labsl_strings -labsl_strings_internal -labsl_malloc_internal \
-labsl_raw_logging_internal -labsl_throw_delegate -labsl_time -labsl_time_zone -labsl_int128 -labsl_base -lre2 \
-lupb -lprotobuf -llibprotoc -lzlib.dll -lssl -lcrypto -ldbghelp

LIBS += -lWS2_32
LIBS += -lAdvapi32 -lbcrypt

DEFINES += _WIN32_WINNT=0x600

注:GRPC_HOME=“C:/Program Files (x86)/grpc” 路径加引号的原因是路径中存在空格。

7.编译运行

分别编译GRpc_HelloWorld_Client和GRpc_HelloWorld_Server。编译完成后,需要将C:\Program Files (x86)\grpc\bin目录下的libzlib.dll库copy到GRpc_HelloWorld_Client.exe和GRpc_HelloWorld_Server.exe所在目录下。
运行GRpc_HelloWorld_Server.exe

在这里插入图片描述
运行GRpc_HelloWorld_Client.exe

在这里插入图片描述
至此Windows下Qt使用grpc介绍完毕。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值