配置python-protobuf解析环境

protobuf是一种跨语言协议,不同语言之间只需定义同一份proto文件,即可实现不同种类的语言的协议沟通。由于工作中使用c++解码较为麻烦,为了提升工作效率,想通过python达到快速解析pb数据的目的(系统为macOS Sierra)。

introduce

出自文章(https://segmentfault.com/a/1190000010098194)

python版本的protobuf安装

首先安装官方protobuf,通过执行protoc命令,可以将proto源文件编译成对应语言的数据结构文件和解析代码,如python对应的文件后缀名通常为.py和.pyc;安装官方,https://github.com/google/protobuf/releases,下载全量源码,然后解压、安装,然后确认安装是否成功。(此外可以通过 brew install protobuf 直接安装)

1
2
3
4
5
6
cd 对应目录
./configure
make
make check
make install
protoc --version

其次,安装对应的python protobuf模块,python引入该模块即可编写代码,实现pb文件的解析。安装python protobuf模块,首先安装pip,mac系统的python自带easy_install,因此直接输入命令:sudo easy_install pip;再通过pip来安装protobuf,命令:pip install protobuf;

遇到的问题:mac下python的six模块版本较低,且由于系统原因,无法被卸载安装新版,而pip在安装protobuf时需要,默认会下载安装较新版本的six模块,因此这里出现了冲突。通过参考该链接,https://github.com/pypa/pip/issues/3165,只需在使用pip安装python模块前,执行该命令即可:

1
pip install --ignore-installed six

使用python解析pb数据流程

这里使用c++对数据进行编码,并生成pb二进制文件,再通过python对pb二进制文件解码,得到c++输入的数据。使用c++写的client程序和python写的server服务器程序通信,在cleint端对数据编码,在server端对数据解码,通信方式采用socket,通信数据格式采用protobuf。

遇到的问题:当c++客户端-c++服务器,数据能正常编码和解析,而c++客户端-python服务器时,服务端python的recv函数接收的数据是null,无法正常接收。

解决方案:怀疑是python接收二进制数据问题,具体原因后续探究。因此把c++编码的protobuf数据再进行base64编码,将二进制proto数据变为字符串,当python服务端收到数据后,先进行base64解码,再对protobuf数据解码。

people.proto源文件:

1
2
3
4
5
6
package demo;
message People {
required string name = 1;
required int32 id = 2;
required string email = 3;
}

切换到对应的proto源文件目录,执行命令,将产出两个文件people.pb.cc 和people.pb.h

1
protoc -I . --c++_out=. people.proto

切换到对应的proto源文件目录,执行以下命令,将产出文件people_pb2.pyc

1
protoc -I . --python_out=. people.proto

c++客户端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <iostream>
#include "people.pb.h"//引入c++对应的proto文件
#include "base64.h"
#define MYPORT 8080
#define BUFFER_SIZE 1024
int main()
{
///定义sockfd
int sock_cli = socket(AF_INET,SOCK_STREAM, 0);
///定义sockaddr_in
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(MYPORT); ///服务器端口
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); ///服务器ip
///连接服务器,成功返回0,错误返回-1
if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("connect");
exit(1);
}
char recvbuf[BUFFER_SIZE];
char sendbuf[BUFFER_SIZE];
int numbytes = (int)recv(sock_cli, recvbuf, BUFFER_SIZE, 0);
recvbuf[numbytes] = '\0';
std::string strbuf = recvbuf;
std::cout << "Client Message: " << strbuf << std::endl;
if(strbuf == "GET PEOPLE")
{
std::string data;
demo::People p;
p.set_name("xionghengheng");
p.set_id(1881409);
p.set_email("xionghengheng@gmail.com");
p.SerializeToString(&data);//protobuf数据编码
char bts[data.length()];
strcpy(bts, data.c_str());
Base64 *base64 = new Base64();
std::string encode = base64->Encode((unsigned char*)bts, data.length());//base64编码
memset(sendbuf, 0, sizeof(sendbuf));
strcpy(sendbuf, encode.c_str());
send(sock_cli, sendbuf, strlen(sendbuf), 0);
}
else
{
send(sock_cli, "Fucking client!\n", 16, 0);
}
memset(recvbuf, 0, sizeof(recvbuf));
close(sock_cli);
return 0;
}

python2.7服务端程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- coding: UTF-8 -*-
import os
import socket
import time
import threading
import people_pb2 as people#引入python proto对应的文件
import base64
def tcplink(sock, addr):
print('Accept new connection from %s:%s...' % addr)
sock.send('GET PEOPLE'.encode())
while True:
data = sock.recv(2048)
time.sleep(1)
if data == 'exit' or not data:
print("no data")
break
else:
data = base64.b64decode(data)#base64解码
peopleItem = people.People()
peopleItem.ParseFromString(data)#protobuf数据解码
print(peopleItem.name)
print(peopleItem.id)
print(peopleItem.email)
sock.close()
print('Connection from %s:%s closed.' % addr)
# 开启ip和端口
ip_port = ('127.0.0.1', 8080)
# 生成句柄
web = socket.socket()
# 绑定端口
web.bind(ip_port)
# 最多连接数
web.listen(5)
# 等待信息
print ('nginx waiting...')
# 开启死循环
while True:
# 接受一个新连接:
sock,addr = web.accept()
# 创建新线程来处理TCP连接:
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()

服务端输出结果:

1
2
3
4
5
6
7
nginx waiting...
Accept new connection from 127.0.0.1:50828...
xionghengheng
1881409
xionghengheng@gmail.com
no data
Connection from 127.0.0.1:50828 closed.