一,源码
1.node.proto文件
package node;
message nodemu{
required bytes mac = 1;
required uint32 time_seen = 2;
required bytes content = 3;
}
message nodeall{
required bytes snum = 1;
repeated nodemu mu = 2;
}
2.test.py文件
#!/usr/bin/env python
import socket
import string
import time
import binascii
import node_pb2
g_server_ip = "192.168.1.23"
g_data_port = 10911
mac = "2312df23a123"
g_mu_mac = ""
for x in xrange(0, len(mac), 2):
g_mu_mac += chr(int(mac[x:x+2], 16))
node = node_pb2.nodeall()
node.snum = '12hdg34422'
mu = node.mu.add()
mu.mac = g_mu_mac
mu.time_seen = int(time.time())
mu.content = '123@qq.com'
node_str = node.SerializeToString()
def send_data(data):
global g_server_ip
global g_data_port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((g_server_ip, g_data_port))
sock.send(data)
sock.close()
def main():
send_data(node_str)
if __name__ == '__main__':
main()
二,实现
1.确保已正确安装python和protobuf(可通过protoc --version查看是否已安装protobuf);
2.protoc -I=./ --python_out=./ ./node.proto 此时会生成node_pb2.py文件;
3.在test.py文件中import node_pb2,这样就可以使用了;
注意:
在运行的时候可能会提示找不到google.protobuf模块,那么请找到protobuf的安装目录,例如cd /usr/local/src/protobuf-2.3.1/python,然后执行
python setup.py build
python setup.py install