본문 바로가기
IT

gRPC 테스트 C++

by Dblog 2021. 6. 7.
728x90

이번엔 c++ 로 grpc 테스트를 진행합니다.

 

 

개발환경

  • ubuntu20.04
  • cmake 3.20

 

이번 테스트에는 make 파일을 이용해서 빌드할 예정입니다.

include, path, .o 파일 만드는게 너무 귀찮습니다..

 

IDL은 이전 python과 같은 형태 입니다.

syntax ="proto3";
package dy;

service PingPongService {
    rpc pingpong (Ping) returns (Pong) {}
}

message Ping
{
    uint32 count=1;    
}

message Pong
{
    uint32 count=1;    
}

 

이번엔 IDL을 따로 protoc로 컴파일 안하고 바로 server/clinet 프로그램을 작성합니다.

나중에 make할때 protoc빌드, include를 할 예정이기 때문에 따로 컴파일하지 않습니다.

pingpong_client.cpp

#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <string>

#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 <grpcpp/grpcpp.h>

#include "pingpong.grpc.pb.h"
#include "pingpong.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Channel;
using grpc::ClientContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;

using dy::PingPongService;
using dy::Ping;
using dy::Pong;

class PingPongClient {
    public:
        PingPongClient(std::shared_ptr<Channel> channel)
            : stub_(PingPongService::NewStub(channel)) {}

        bool pingpong(const int& pci_phycellid){
            Ping requset;
            requset.set_count(1);

            Pong reply;

            ClientContext context;

            // The actual RPC.
            Status status = stub_->pingpong(&context, requset, &reply);
            
            std::cout << "received // " << reply << std::endl;
            std::cout << "received // " << status.code << std::endl;
            if (status.ok()) {
                std::cout <<  " :::111:::: "  << std::endl;
                return reply.count();
            } else {
                std::cout <<  " :::222:::: "  << std::endl;
                std::cout << status.error_code() << ": " << status.error_message() << std::endl;
                return false;
            }
            std::cout <<  " :::333:::: "  << std::endl;
            return true;
        }
    private:
        std::unique_ptr<PingPongService::Stub> stub_;
};

int main(int argc, char** argv)
{   
    PingPongClient pcicli( grpc::CreateChannel("0.0.0.0:50051", grpc::InsecureChannelCredentials()));
    bool reply = pcicli.pingpong(32);
    std::cout << "Greeter received: " << reply << std::endl;
    return 0;
}

 

pingpong_server.cpp

#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <string>

#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 "pingpong.grpc.pb.h"
#include "pingpong.pb.h"

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerReader;
using grpc::ServerReaderWriter;
using grpc::ServerWriter;
using grpc::Status;

using dy::PingPongService;
using dy::Ping;
using dy::Pong;

class Listener final : public PingPongService::Service {
    Status pingpong(ServerContext* context, const Ping* ping, Pong* pong) override{
        pong->set_count(12);
        return Status::OK;
    }
};

void Run()
{
    std::string server_address("0.0.0.0:50051");
    Listener service;

    grpc::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)
{
    Run();
    return 0;
}

 

이번엔 make를 사용해서 빌드할예정이기에 Makefile이 필요합니다. 또한 CMakeLists.txt 파일도 추가로 필요합니다.

Makefile

#
# 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.
#

HOST_SYSTEM = $(shell uname | cut -f 1 -d_)
SYSTEM ?= $(HOST_SYSTEM)
CXX = g++
CPPFLAGS += `pkg-config --cflags protobuf grpc`
CXXFLAGS += -std=c++11
ifeq ($(SYSTEM),Darwin)
LDFLAGS += -L/usr/local/lib `pkg-config --libs protobuf grpc++`\
					 -pthread\
           	-lgrpc++_reflection\
           	-ldl
			-lssl \
		   	-lcrypto
else
LDFLAGS += -L/usr/local/lib `pkg-config --libs protobuf grpc++`\
           	-pthread\
           	-Wl,--no-as-needed -lgrpc++_reflection -Wl,--as-needed\
           	-ldl
			-lssl \
		   	-lcrypto
endif
PROTOC = protoc
GRPC_CPP_PLUGIN = grpc_cpp_plugin
GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)`

PROTOS_PATH = .

vpath %.proto $(PROTOS_PATH)

all: system-check pingpong_client pingpong_server

pingpong_client: pingpong.pb.o pingpong.grpc.pb.o pingpong_client.o 
	$(CXX) $^ $(LDFLAGS) -o $@

pingpong_server: pingpong.pb.o pingpong.grpc.pb.o pingpong_server.o 
	$(CXX) $^ $(LDFLAGS) -o $@

%.grpc.pb.cc: %.proto
	$(PROTOC) -I $(PROTOS_PATH) --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $<

%.pb.cc: %.proto
	$(PROTOC) -I $(PROTOS_PATH) --cpp_out=. $<

clean:
	rm -f *.o *.pb.cc *.pb.h pingpong_client pingpong_server


# The following is to test your system and ensure a smoother experience.
# They are by no means necessary to actually compile a grpc-enabled software.

PROTOC_CMD = which $(PROTOC)
PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3
PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN)
HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false)
ifeq ($(HAS_PROTOC),true)
HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false)
endif
HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false)

SYSTEM_OK = false
ifeq ($(HAS_VALID_PROTOC),true)
ifeq ($(HAS_PLUGIN),true)
SYSTEM_OK = true
endif
endif

system-check:
ifneq ($(HAS_VALID_PROTOC),true)
	@echo " DEPENDENCY ERROR"
	@echo
	@echo "You don't have protoc 3.0.0 installed in your path."
	@echo "Please install Google protocol buffers 3.0.0 and its compiler."
	@echo "You can find it here:"
	@echo
	@echo "   https://github.com/google/protobuf/releases/tag/v3.0.0"
	@echo
	@echo "Here is what I get when trying to evaluate your version of protoc:"
	@echo
	-$(PROTOC) --version
	@echo
	@echo
endif
ifneq ($(HAS_PLUGIN),true)
	@echo " DEPENDENCY ERROR"
	@echo
	@echo "You don't have the grpc c++ protobuf plugin installed in your path."
	@echo "Please install grpc. You can find it here:"
	@echo
	@echo "   https://github.com/grpc/grpc"
	@echo
	@echo "Here is what I get when trying to detect if you have the plugin:"
	@echo
	-which $(GRPC_CPP_PLUGIN)
	@echo
	@echo
endif
ifneq ($(SYSTEM_OK),true)
	@false
endif

 

CMakeLists.txt

# Copyright 2018 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.
#
# cmake build file for C++ pci example.
# Assumes protobuf and gRPC have been installed using cmake.
# See cmake_externalproject/CMakeLists.txt for all-in-one cmake build
# that automatically builds all the dependencies before building pci.

cmake_minimum_required(VERSION 3.5.1)

project(RouteGuide C CXX)

include(../cmake/common.cmake)

# Proto file
get_filename_component(rg_proto "pingpong.proto" ABSOLUTE)
get_filename_component(rg_proto_path "${rg_proto}" PATH)

# Generated sources
set(rg_proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/pingpong.pb.cc")
set(rg_proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/pingpong.pb.h")
set(rg_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/pingpong.grpc.pb.cc")
set(rg_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/pingpong.grpc.pb.h")
add_custom_command(
      OUTPUT "${rg_proto_srcs}" "${rg_proto_hdrs}" "${rg_grpc_srcs}" "${rg_grpc_hdrs}"
      COMMAND ${_PROTOBUF_PROTOC}
      ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}"
        --cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
        -I "${rg_proto_path}"
        --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
        "${rg_proto}"
      DEPENDS "${rg_proto}")

# Include generated *.pb.h files
include_directories("${CMAKE_CURRENT_BINARY_DIR}")

# rg_grpc_proto
add_library(rg_grpc_proto
  ${rg_grpc_srcs}
  ${rg_grpc_hdrs}
  ${rg_proto_srcs}
  ${rg_proto_hdrs})
target_link_libraries(rg_grpc_proto
  ${_REFLECTION}
  ${_GRPC_GRPCPP}
  ${_PROTOBUF_LIBPROTOBUF})


# Targets pingpong_(client|server)
foreach(_target
  pingpong_client pingpong_server)
  add_executable(${_target}
    "${_target}.cc")
  target_link_libraries(${_target}
    rg_grpc_proto
    ${_REFLECTION}
    ${_GRPC_GRPCPP}
    ${_PROTOBUF_LIBPROTOBUF})
endforeach()

 

BUILD Command

// grpc example cpp 폴더에서 진행, (git clone 받았던 폴더입니다.)
rm -rf cmake/
mkdir -p cmake/build
cd cmake/build
cmake -DCMAKE_PREFIX_PATH=$MY_INSTALL_DIR ../..
make pingpong.grpc.pb.o
make

 

 

728x90

'IT' 카테고리의 다른 글

TPM(Trusted Platform Module)  (0) 2021.06.25
RPC, IPC 그리고 gRPC  (0) 2021.06.14
gRPC 테스트 python  (0) 2021.06.01
gRPC 설치 - c++  (0) 2021.06.01
[LINUX] 리눅스 명령어,  (0) 2021.03.18

댓글