Python XML RPC服务器端和客户端实例
一、远程过程调用rpc
xml-rpc is a remote procedure call method that uses xml passed via http as a transport. with it, a client can call methods with parameters on a remote server (the server is named by a uri) and get back structured data. this module supports writing xml-rpc client code; it handles all the details of translating between conformable python objects and xml on the wire.
简单地,client可以调用server上提供的方法,然后得到执行的结果。类似与webservice。
推荐查看xmlprc的源文件:c:\python31\lib\xmlrpc
二、实例
1) server
from xmlrpc.server import simplexmlrpcserver
from xmlrpc.server import simplexmlrpcrequesthandler
def div(x,y):
return x - y
class math:
def _listmethods(self):
# this method must be present for system.listmethods
# to work
return ['add', 'pow']
def _methodhelp(self, method):
# this method must be present for system.methodhelp
# to work
if method == 'add':
return "add(2,3) => 5"
elif method == 'pow':
return "pow(x, y[, z]) => number"
else:
# by convention, return empty
# string if no help is available
return ""
def _dispatch(self, method, params):
if method == 'pow':
return pow(*params)
elif method == 'add':
return params[0] + params[1]
else:
raise 'bad method'
server = simplexmlrpcserver(("localhost", 8000))
server.register_introspection_functions()
server.register_function(div,"div")
server.register_function(lambda x,y: x*y, 'multiply')
server.register_instance(math())
server.serve_forever()
2)client
import xmlrpc.client
s = xmlrpc.client.serverproxy('http://localhost:8000')
print(s.system.listmethods())
print(s.pow(2,3)) # returns 28
print(s.add(2,3)) # returns 5
print(s.div(3,2)) # returns 1
print(s.multiply(4,5)) # returns 20
3)result
上一篇: 用Python编写一个国际象棋AI程序
推荐阅读
-
Python通过DOM和SAX方式解析XML的应用实例分享
-
Python XML RPC服务器端和客户端实例
-
python 通过xml获取测试节点和属性的实例
-
python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
-
python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
-
python网络编程之UDP通信实例(含服务器端、客户端、UDP广播例子)
-
Python XML RPC服务器端和客户端实例
-
Python通过DOM和SAX方式解析XML的应用实例分享
-
Python XML RPC服务器端和客户端实例
-
Python通过DOM和SAX方式解析XML的应用实例分享