天天看點

Google protobuf的安裝及使用

最近應為工作的需要,合作的部門提供了protobuf的接口,總結了一下使用的過程和方法如下:  

下載下傳protobuf-2.3.0:  

    http://protobuf.googlecode.com/files/protobuf-2.3.0.zip  

安裝:   

unzip protobuf-2.3.0.zip  

cd protobuf-2.3.0  

./configure  

make   

make check   

make install  

結果:  

Libraries have been installed in:  

   /usr/local/lib  

Head files hava been installed in:  

/usr/local/include/google/  

protobuf/  

開始寫.proto檔案:  

BaseMessage.proto:  

message MessageBase  

{  

    required int32 opcode = 1;  

    // other: sendMgrId, sendId, recvMgrId, recvId, ...  

}  

message BaseMessage  

    required MessageBase msgbase = 1;  

BaseMessage.proto是其它消息proto檔案的基礎,以容器子產品的C2S_GetContainerInfo為例:  

ContainerMessage.proto:  

import "BaseMessage.proto";  

message C2SGetContainerInfoMsg  

    optional int32 containerType = 2;  

.proto檔案編寫規則:  

1)所有消息都需要包含msgbase這項,并編号都為1,即:  

  required MessageBase msgbase = 1;  

2)除了msgbase這項寫成required外,其它所有項都寫成optional。  

編譯 .proto 檔案  

protoc -I=. --cpp_out=. BaseMessage.proto  

protoc -I=. --cpp_out=. ContainerMessage.proto  

生成BaseMessage.pb.h、BaseMessage.pb.cc  

    ContainerMessage.pb.h、ContainerMessage.pb.cc  

将它們添加到工程檔案中。  

編寫C++代碼:  

1)發送消息:  

C2SGetContainerInfoMsg msg;  

msg.mutable_msgbase()->set_opcode(C2S_GetContainerInfo);  

msg.set_containertype(1);  

std::string out = msg.SerializeAsString();  

send(sockfd, out.c_str(), out.size(), 0);  

2)接收消息  

char buf[MAXBUF + 1];  

int len;  

bzero(buf, MAXBUF + 1);  

len = recv(new_fd, buf, MAXBUF, 0);  

if (len > 0)  

    printf("%d接收消息成功:'%s',共%d個位元組的資料/n",  

            new_fd, buf, len);  

    BaseMessage baseMsg;  

    std::string data = buf;  

    baseMsg.ParseFromString(data);  

    int opcode = baseMsg.mutable_msgbase()->opcode();  

    printf("opcode=%d/n", opcode);  

    switch (opcode)  

    {  

    case C2S_GetContainerInfo:  

        C2SGetContainerInfoMsg msg;  

        msg.ParseFromString(data);  

        printf("containerType=%d/n", msg.containertype());  

        break;  

    }  

    default:  

else  

    if (len < 0)  

        printf("消息接收失敗!錯誤代碼是%d,錯誤資訊是'%s'/n",  

             errno, strerror(errno));  

    close(new_fd);  

    return -1;  

編譯C++代碼:  

Need to link lib:  

protobuf  

pthread  

參考:   

1,http://www.360doc.com/content/10/0822/16/11586_47942017.shtml  

2,http://code.google.com/p/protobuf/  

原文位址:http://blog.csdn.net/ganghust/article/details/6115283

2、make

3、make check

4、make install(需要超級使用者root權限)

繼續閱讀