模块:
SimpleXMLRPCServer
python标准库中自带的模块,无需另外安装
在python3中 SimpleXMLRPCServer已经被合并到xmlrpc.server
定义:
class SimpleXMLRPCServer.SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]])
方法:
1.SimpleXMLRPCServer.register_function(function[, name])
注册一个方法,服务
2.SimpleXMLRPCServer.register_instance(instance[, allow_dotted_names])
注册实例
一个对象在register_function注册后则,不能再在register_instance注册
3.SimpleXMLRPCServer.register_introspection_functions()
注册一个反函数
4.SimpleXMLRPCServer.register_multicall_functions()
注册复合函数
例如:
服务端
from SimpleXMLRPCServer import SimpleXMLRPCServer
def respon_string(str):
return "get string :%s"%str
if __name__ == '__main__':
s = SimpleXMLRPCServer(('0.0.0.0', 8080))
s.register_function(respon_string,"get_string")
s.serve_forever()
客服端
from xmlrpclib import ServerProxy
if __name__ == '__main__':
s = ServerProxy("http://192.168.137.9:8080")
print s.get_string("hello")
结果:
# python get.py
get string :hello
服务端:
#coding=utf8
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
server = SimpleXMLRPCServer(("0.0.0.0", 8000),
requestHandler=RequestHandler)
print "start service on 0.0.0.0:8000"
server.register_introspection_functions()
#注册pow,幂运算,实际调用的是已有的算数pow()
server.register_function(pow)
def add(x,y):
return x + y
server.register_function(add, 'add')
#注方法在xml-rpc中都是public的
class fun:
def div(self, x, y):
return x // y
server.register_instance(fun())
server.serve_forever()
客服端:
可以使用下面的方法调用:
import xmlrpclib
s = xmlrpclib.ServerProxy('http://192.168.137.9:8000')
print s.pow(3,5)
print s.add(3,9)
print s.div(7,3)
print s.system.listMethods()
结果:
243
12
2
['add', 'div', 'pow', 'system.listMethods', 'system.methodHelp', 'system.methodSignature']
register_multicall_functions实现复合调用,多个方法注册到一个调用里
#coding=utf8
from SimpleXMLRPCServer import SimpleXMLRPCServer
server = SimpleXMLRPCServer(("0.0.0.0", 8000))
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_multicall_functions()
server.serve_forever()
MultiCall调用复合方法
import xmlrpclib
s = xmlrpclib.ServerProxy("http://192.168.137.9:8000")
print s
multi = xmlrpclib.MultiCall(s)
multi.pow(2, 5)
try:
for response in multi():
print response
except Error, err:
print "ERROR", err
结果:
# python jm.py
for 192.168.137.9:8000/RPC2>
32