ProtoBuf的Socket中應用示例

2021-09-30 01:46:17 字數 3565 閱讀 2338

寫了乙個socket通訊下的protobuf示例,三個檔案:

syntax =

"proto3"

;

package demo;

message helloprotobuf

編譯命令:

protoc -i=./ --cpp_out=./ helloprotobuf.proto

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

//for protobuf

#include

"helloprotobuf.pb.h"

#define port 12345

#define queue 20

int conn;

void

thread_task()

intmain()

if(listen

(socketservice, queue)==-

1)struct sockaddr_in client_addr;

socklen_t length =

sizeof

(client_addr)

; conn =

accept

(socketservice,

(struct sockaddr*

)&client_addr,

&length);if

( conn <0)

demo::helloprotobuf msg1;

char buffer[

2048];

while

(true

)printf

("] size = %d\n"

, len)

; msg1.

parsefromarray

(buffer, len)

;printf

("%s\n"

, msg1.

str().

c_str()

);if(

strcmp

(msg1.

str().

c_str()

,"exit")==

0)break;}

close

(conn)

;close

(socketservice)

;return0;

}

編譯命令:

g++ -std=c++11 service.cpp helloprotobuf.pb.cc -o service -i/usr/local/protobuf/include -l/usr/local/protobuf/lib -lprotobuf

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

"helloprotobuf.pb.h"

#define myport 12345

#define buffer_size 1024

intmain()

char sendbuf[buffer_size]

;char inbuf[buffer_size]

;memset

(sendbuf,0,

sizeof

(sendbuf));

memset

(inbuf,0,

sizeof

(inbuf));

while

(fgets

(inbuf,

sizeof

(inbuf)

,stdin)!=

null

)printf

("] size = %d\n"

, i)

;send

(socketclient, sendbuf,

strlen

(sendbuf),0

);if(

strcmp

(inbuf,

"exit")==

0)break

;memset

(sendbuf,0,

sizeof

(sendbuf));

memset

(inbuf,0,

sizeof

(inbuf));

}close

(socketclient)

;return0;

}

編譯命令:

g++ -std=c++11 client.cpp helloprotobuf.pb.cc -o client -i/usr/local/protobuf/include -l/usr/local/protobuf/lib -lprotobuf

執行程式,列印資訊:

客戶端:(依次測試3次,分別輸入abcdef、ghijk、lmn)

abcdef

in[abcdef] strlen = 6

serializetoarray =

[0a 06 61 62 63 64 65 66 ] size = 8

ghijk

in[ghijk] strlen = 5

serializetoarray =

[0a 05 67 68 69 6a 6b ] size = 7

lmn

in[lmn] strlen = 3

serializetoarray =

[0a 03 6c 6d 6e ] size = 5

服務端:(依次接收3次)

size = 8

getarrayfromclient =

[0a 06 61 62 63 64 65 66 ] size = 8

abcdef

size = 7

getarrayfromclient =

[0a 05 67 68 69 6a 6b ] size = 7

ghijk

size = 5

getarrayfromclient =

[0a 03 6c 6d 6e ] size = 5

lmn

注:

protoBuf的優缺點

protobuf 有如 xml,不過它更小 更快 也更簡單。你可以定義自己的資料結構,然後使用 生成器生成的 來讀寫這個資料結構。你甚至可以在無需重新部署程式的情況下更新資料結構。只需使用 protobuf 對資料結構進行一次描述,即可利用各種不同語言或從各種不同資料流中對你的結構化資料輕鬆讀寫。它...

protobuf的使用 三

rpc方法的序列化和反序列化 rpc標籤 在protobuf中定義描述rpc方法的型別 service 在proto檔案中增加rpc服務的選項 表示生成service服務類和rpc方法描述,預設是不生成的 option cc generic services true message loginre...

protobuf的簡單使用

作業系統 centos7.3.1611 x64 gcc版本 4.8.5 go 版本 go1.8.3 linux amd64 python 版本 2.7.5 libprotoc 2.5.0 protobuf是google開發一種資料描述語言,能夠將結構化資料序列化,可用於資料儲存 通訊協議等方面。首頁...