多语言跨平台序列化框架Google Protobuf-Python connect Netty

Python Protobuf模块安装

在[text][https://pypi.python.org/pypi]下载protobuf-2.5.0.tar.gz.

注意,该protobuf-2.5.0.tar.gz和上一节下载的文件名相同,但内容不一样. 上一节下载的是Linux软件库,该文件是一个Python模块.

安装:

tar zxvf protobuf-2.5.0.tar.gz
cd protobuf-2.5.0
sudo python setup.py install

安装好Python Protobuf模块后, 就可以进行下一步.

生成command.proto的Python代码

protoc --python_out=./ command.proto

生成的Python文件名为:command_pb2.py, 把command_pb2.py放入项目空间.

一个简单的Python Socket服务

#!/usr/bin/env python
#!encoding:utf-8

import sys
import socket
import time

__author__ = 'zhenqin'

class SocketService():
    def __init__(self, host = "localhost", port = 8080):
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.s.connect((host , port))
        except socket.error, msg:
            print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
            sys.exit()

    def send(self, message):
        self.s.sendall(message)

    def recv(self, buff = 4096):
        return self.s.recv(buff)

    def __del__(self):
        self.s.close()

if __name__ == '__main__':
    s = SocketService()

稍微熟悉Python的应该能看的出来, 上面定义了一个Socket Client服务,SocketService类实例化后能和服务端建立连接,通过send发送消息,recv接收消息.

和Netty通信

编写Python, 命名为:protobuf_test.py

#!/usr/bin/env python
#!encoding:utf-8

import google.protobuf
import command_pb2
import time
import socketredirect

def testProtoBufSocket():
    #建立连接
    rpc = socketredirect.SocketService(host = "zhenqin-k45vm", port = 8080)

    #构造一个Request实例
    tse = command_pb2.RequestCommand()
    tse.auth = "aaaaaaaaaaaa"
    tse.command = "shutdown"

    #向服务器端发送消息
    rpc.send(tse.SerializeToString())
    print 'Message send successfully'
    reply = rpc.recv(4096)

    #接收消息后反序列化
    test = command_pb2.ResponseCommand()
    test.ParseFromString(reply)

    #输出
    print test.success,test.message

if __name__ == '__main__':
    testProtoBufSocket()

程序代码都不难理解. 构造一个简单的Request发送到服务端, 并且接收返回的Response.

运行上一节里的Netty Server程序, 然后运行protobuf_test.py, 可以看到一个完整的通信过程.

Server:

08-26 14:51:28 [INFO] [handler.ProtobufChannelHandler(44)] aaaaaaaaaaaa, shutdown

Client:

Message send successfully
True OK

这个过程两边的Bean的序列化和反序列化对程序员都是透明的.这也就是程序员只需要处理业务逻辑,而在两边你都将得到的是一个Bean.

至此, 我已经把Protobuf简单的介绍完了.

你可能感兴趣的:(python,netty,protobuf)