python xml-rpc远程过程调用

版权声明:分享才能发挥最大的价值 https://blog.csdn.net/qq_32252957/article/details/82588040

各种语言都有很多框架支持远程过程调用,下面是对于xml-rpc的说明

XML-RPC is a remote procedure call (RPCprotocol which usesXML to encode its calls and HTTP as a transport mechanism. "XML-RPCalso refers generically to the use of XML for remoteprocedure callindependently of the specific protocolThis articleis about the protocol named "XML-RPC".

意思是XML-RPC是一个使用xml来对调用进行编码(服务函数名,参数,返回值结果等,一般也可以用json,序列化的形式),用http协议来进行传输的远程过程协议。

服务端server.py

"""
服务端代码
"""
from concurrent import futures
from SimpleXMLRPCServer  import SimpleXMLRPCServer 
from SimpleXMLRPCServer  import SimpleXMLRPCRequestHandler
from SocketServer import ThreadingMixIn

__HOST = 'localhost'
__PORT = 8000

class RequestHandler(SimpleXMLRPCRequestHandler):
	rpc_paths = ('/RPC2') #定义RPC接口的请求地址

class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
	pass

server = ThreadXMLRPCServer((__HOST, __PORT), requestHandler = RequestHandler, allow_none=True)
server.register_introspection_functions() 

# server.register_function(func, 'add') func是服务点定义的函数,add是客户端调用时用的函数
server.register_function(pow)

def adder_function(x, y):
	return x + y
server.register_function(adder_function, 'add')

class MyFuncs:
	def div(self, x, y):
		return x //y


server.register_instance(MyFuncs()) #将类中的方法全部注册到server端

server.serve_forever()

客户端,我写两个以便于调试,另外服务端使用了ThreadingMixIn多线程套接字支持。

client.py

import xmlrpclib

__HOST = 'localhost'
__PORT = '8000'

s = xmlrpclib.ServerProxy('http://' + __HOST + ':' + __PORT)
print s.pow(2, 3)
print s.add(2, 3)
print s.div(5, 2)

print s.system.listMethods()

client1.py

import xmlrpclib

__HOST = 'localhost'
__PORT = '8000'

s = xmlrpclib.ServerProxy('http://' + __HOST + ':' + __PORT)
# print s.pow(2, 3)
print s.add(2, 3)
print s.div(5, 2)

print s.system.listMethods()

猜你喜欢

转载自blog.csdn.net/qq_32252957/article/details/82588040