gRPC C++ demo

.proto生成c++代码指令

protoc.exe --grpc_out=. --plugin=protoc-gen-grpc=.\grpc_cpp_plugin.exe position_detection.proto
protoc.exe --cpp_out=. position_detection.proto

单项 RPC

helloworld.proto

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

服务端

#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

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

// 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() {
  grpc::EnableDefaultHealthCheckService(true);
  grpc::reflection::InitProtoReflectionServerBuilderPlugin();   //注册反射机制

  std::string server_address("127.0.0.1:50051");
  GreeterServiceImpl service;

  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) {
  RunServer();

  return 0;
}

客户端

#include <iostream>
#include <memory>
#include <string>

#include <grpcpp/grpcpp.h>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

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

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) {
  // Instantiate the client. It requires a channel, out of which the actual RPCs
  // are created. This channel models a connection to an endpoint (in this case,
  // localhost at port 50051). We indicate that the channel isn't authenticated
  // (use of InsecureChannelCredentials()).
  GreeterClient greeter(grpc::CreateChannel("127.0.0.1:50051", grpc::InsecureChannelCredentials()));
  std::string user("world");
  std::string reply = greeter.SayHello(user);
  std::cout << "Greeter received: " << reply << std::endl;

  std::cin.get();
  return 0;
}

服务端流RPC

position_detection.proto

syntax = "proto3";

package PositionDetection;

message RunMessage{
	string imgPath = 1;
}

message RunResponse{
	bool believable = 1;
	string responseJson = 2;
}

service ChatService {
    rpc run(RunMessage) returns (stream RunResponse);
}

服务端

#include <grpcpp/grpcpp.h>
#include "protobuf/position_detection.grpc.pb.h"
#include "protobuf/position_detection.pb.h"

class DetectionServiceImpl final : public PositionDetection::ChatService::Service
{
public:
	DetectionServiceImpl();
	~DetectionServiceImpl();

	::grpc::Status run(::grpc::ServerContext* context, const ::PositionDetection::RunMessage* request,::grpc::ServerWriter< ::PositionDetection::RunResponse>* writer)
	{
		std::string imgPath = request->imgpath();

		if (m_pIDetectionBase != nullptr)
		{
			::PositionDetection::RunResponse response;
			response.set_believable(true);
			response.set_responsejson("xxxxxx");
			writer->Write(response);
			return ::grpc::Status::OK;
		}
		else 
		{
			return ::grpc::Status::CANCELLED;
		}
	}
};

void RunServer() {
	std::string server_address(Cfg::GetInstance()->GetBaseCfg().ipAddress);
	DetectionServiceImpl service;

	::grpc::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);
	builder.SetMaxMessageSize(INT_MAX);
	// Finally assemble the server.
	std::unique_ptr<::grpc::Server> server(builder.BuildAndStart());
	Logger::GetLogger()->info("Server listening on {}", server_address);
	// 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[]) 
{
	RunServer();

	return 0;
}

客户端

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

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using PositionDetection::RunMessage;
using PositionDetection::RunResponse;
using PositionDetection::ChatService;

class GreeterClient {
public:
    bool believable;
    std::string strRespone;
public:
    GreeterClient(std::shared_ptr<Channel> channel) : stub_(ChatService::NewStub(channel)) {}

    // Assembles the client's payload, sends it and presents the response back
    // from the server.
    void runMessage(const std::string& imgPath)
    {
        // Data we are sending to the server.
        RunMessage message;
        message.set_imgpath(imgPath);

        // Container for the data we expect from the server.
        //RunResponse response;

        // Context for the client. It could be used to convey extra information to
        // the server and/or tweak certain RPC behaviors.
        ClientContext context;
        RunResponse responseMessage;
        // The actual RPC.
        std::unique_ptr< ::grpc::ClientReader< ::PositionDetection::RunResponse>> response = stub_->run(&context, message);

        if (response->Read(&responseMessage))
        {
            std::cout << responseMessage.believable() << std::endl;
            std::cout << responseMessage.responsejson() << std::endl;
        }
        else
        {
            std::cout << "run error" << std::endl;
        }

    }

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

int main(int argc, char** argv) {
    // Instantiate the client. It requires a channel, out of which the actual RPCs
    // are created. This channel models a connection to an endpoint (in this case,
    // localhost at port 50051). We indicate that the channel isn't authenticated
    // (use of InsecureChannelCredentials()).
    GreeterClient greeter(grpc::CreateChannel("localhost:50051", grpc::InsecureChannelCredentials()));

    std::string imgPath = "xxxxx";
    greeter.runMessage(imgPath);

    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值