最近看PYTHON RPC, 看了下帮助文档,把代码总结如下:
服务端#!/usr/bin/env python
#-*- coding=utf-8 -*-
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
import datetime
class MyFuncs:
def div(self, x, y) : return x // y
def is_even(n):
return n%2 == 0
#process datetime
def today():
today=datetime.datetime.today()
return xmlrpclib.DateTime(today)
#process binary data
def python_logo():
with open("py.png", "rb") as handle:
return xmlrpclib.Binary(handle.read())
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.register_function(today, "today")
server.register_function(python_logo,"python_logo")
print 'register mulitcall'
server.register_multicall_functions()
#如果是一个CLASS的话,还可以 Register an instance 这样的话,这个CLASS中所有的 function 都被注册了。
server.register_instance(MyFuncs())
server.serve_forever()
客户端:
#!/usr/bin/env python
import xmlrpclib
import datetime
proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
"""
print "3 is even: %s" % str(proxy.is_even(3))
print "100 is even: %s" % str(proxy.is_even(100))
print '====get datetime========================'
today=proxy.today()
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")
print '====get binary data====================='
with open("fetch_py.png", "wb") as handle:
handle.write(proxy.python_logo().data)
"""
print '====mulitple functions test============='
multicall=xmlrpclib.MultiCall(proxy)
multicall.is_even(3)
multicall.today()
result=multicall()
print '===multiple result======================'
print tuple(result)
个人感觉比JAVA 的RPC 简单,方便。