2017년 10월 8일 일요일

[Linux/CentOS/ProtoBuf] Centos - Protobuf 연동[echo 서버][2]






아래 포스팅에서의 작업은 다음과 같습니다.


1. *.proto 생성방법
2. 간단한 Echo 서버 및 Makefile 작성
3. 통신 테스트




1. *.proto 생성방법

ProtoBuf 통신을 위해서는 *.proto , *.pb 관련 파일을 생성해야 합니다.

이게 무엇인가하면,

ProtoBuffer는 객체를 byte화 시키고(Serialize) Client쪽에서도 byte를 객체로(DeSerialize) 변환을 진행합니다.
(통신에는 byte stream으로만 통신하기 때문에)


[Serialize]





















[DeSerialize]
































즉, Protocol과 같은 역활을 진행하기 때문에, Client - Server간에 Protocol에 해당하는 명세서를 작성한다고 생각하시면 편할것 같습니다.

그럼 이거를 수동으로 만드냐? 그건 아닙니다.
ProtoBuffer에 프로그램이 존재하는데, 만드는 방법은 다음과 같습니다.


protoc 프로그램을 통해, 정의된 *.proto를 *.pb로 생성하는 역활을 진행합니다.
protoc 실행방법은 아래와 같습니다. (경로 = protobuf 메인/src/protoc )


protoc -I=../../../ProjectRTS/ClientRoot/proto --csharp_out=../../../ProjectRTS/ClientRoot/proto ../../../ProjectRTS/ClientRoot/proto/addressbook.proto

-I에는 *.proto가 있는 경로
output에는 *.pb로 생성 될 경로

그 뒤의 경로는 어느 *.proto를 바꿀지 정의합니다.

해당 명령어는 C#에 해당하는 건데, c++의 경우는 --csharp_out을 단순 --cpp_out으로 변환하면 됩니다.

해당 명령을 진행하면 어떻게 되느냐?

/* 해당 정의된 Package들이 *.pb.cc 와 *.pb.h로 생성됩니다. */ 
syntax = "proto3";

package tutorial;

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}


코드 길이가 긴관계로 addressbook.pb.h만 보여드리겠습니다.


class Person_PhoneNumber : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tutorial.Person.PhoneNumber) */ {
 public:
  Person_PhoneNumber();
  virtual ~Person_PhoneNumber();

  Person_PhoneNumber(const Person_PhoneNumber& from);

  inline Person_PhoneNumber& operator=(const Person_PhoneNumber& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _internal_metadata_.unknown_fields();
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return _internal_metadata_.mutable_unknown_fields();
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const Person_PhoneNumber& default_instance();

  static inline const Person_PhoneNumber* internal_default_instance() {
    return reinterpret_cast(
               &_Person_PhoneNumber_default_instance_);
  }
  static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
    0;

  void Swap(Person_PhoneNumber* other);

  // implements Message ---------------------
   ....

  /* 각각의 Message에 대해 Class 및 getter setter가 작성됨 */ 


위의 *.pb.cc와 *.pb.h를 통해 Main Project와 빌드 후, 링킹하여 사용합니다.


2. 간단한 Echo 서버 작성 및 Makefile 작성

MakeFile 부
# Makefile, pb.h와 pb.cc를 빌드 후,  

APP_SRCS=$(wildcard *.cpp)
PROTO_SRCS= ../proto/addressbook.pb.cc


APP_OBJS=$(APP_SRCS:.cpp=.o)
PROTO_OBJS= ../proto/addressbook.pb.o



INCLUDES=-I./ -I../proto -I../include -I../
LIBRARY=-L../lib -lprotobuf-lite -lprotobuf -lprotoc


all: Project


$(PROTO_OBJS): $(PROTO_SRCS)
    $(CXX) $(CXXFLAGS) $(INCLUDES) -c -o $@ $<

.cpp.o:
    $(CXX) $(CXXFLAGS) $(INCLUDES) -c -o $@ $<



Project : $(APP_OBJS) $(PROTO_OBJS)
    $(CXX) $(CXXFLAGS) $(PROTO_OBJS)  $(INCLUDES) $(LIBRARY) $< -o $@

clean:
    rm -f *.o ../proto/*.o Project


C++ Echo Server Main 코드
#include "iostream"
#include "string"
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "arpa/inet.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"

#include "proto/addressbook.pb.h"

#define LOG printf
using namespace std;
using namespace google::protobuf::io;

#define READ_BUFSIZE 8096
#define BACKLOG_SIZE 50
int main(int argc, char* argv[]) {
    // Verify that the version of the library that we linked against is
    // compatible with the version of the headers we compiled against.
    GOOGLE_PROTOBUF_VERIFY_VERSION;


    /************************
     * Serv Socket Declare
     ************************/
    int serverSock;
    int port = 10001;
    struct sockaddr_in serverAddr;

    serverSock = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSock <= 0)
    {
        LOG("Error Socket Open");
        perror("socket:");
        return -1;
    }

    memset(&serverAddr, '\0', sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddr.sin_port = htons(port);

    if ( bind(serverSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) < 0 )
    {
        LOG("Serv SOck Bind Error\n");
        perror("bind");
        return -1;
    }

    if ( listen(serverSock , BACKLOG_SIZE) < 0 )
    {
        LOG("Errror List\n");
        perror("listen:");
        return -1;
    }

    /**************************
     * Read Protocol Buffer
     **************************/
    size_t servAddrSize = sizeof(serverAddr);

    struct sockaddr_in clntAddr;
    int clntAddrSize = sizeof(clntAddr);
    int clientSock = accept(serverSock, (sockaddr*)&clntAddr, (socklen_t*)&clntAddrSize);
    if ( clientSock < 0 )
    {
        LOG("Error Client Set\n");
        perror("accept");
    }
    while(true)
    {
        memset(buffer, '\0', (size_t)READ_BUFSIZE);
        int32_t readSize;
        LOG("accept Success\n");
        if ( (readSize = recv(clientSock, buffer, (int32_t)READ_BUFSIZE, 0)) > 0 )
        {
            LOG("buffer:[%s]", buffer);
            tutorial::AddressBook addressBook;
            /**************************************
             * Read Buffer Save inputStream
             * And Get Size used by ReadVariant32
             * Parsing addressBook
             *************************************/
            google::protobuf::uint32 pbufSize;
            google::protobuf::io::ArrayInputStream inputStream(buffer, readSize);
            CodedInputStream codedStream(&inputStream);
            codedStream.ReadVarint32(&pbufSize);

            google::protobuf::io::CodedInputStream::Limit bufferLimit = codedStream.PushLimit(pbufSize);
            addressBook.ParseFromCodedStream(&codedStream);
            codedStream.PopLimit(bufferLimit);
            cout << "Message is " << addressBook.DebugString();

            /**************************************
             * Write Buffer
             **************************************/
            int32_t writeSize;
            if ( (writeSize = send(clientSock, buffer, (size_t)readSize, MSG_WAITALL) ) < 0 )
            {
                LOG("Error Send");
                perror("send");
            }

        }
    // Optional:  Delete all global objects allocated by libprotobuf.
    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

서버(Linux) - 클라이언트(Unity)


















댓글 없음:

댓글 쓰기