1. Let’s talk about the conclusion first: using the xml-rpc mechanism can easily implement RPC calls between servers.
2. The test results are as follows:
3. The source code is as follows:
The source code of the server side is as follows:
import operator, math from SimpleXMLRPCServer import SimpleXMLRPCServer from functools import reduce def main(): server = SimpleXMLRPCServer(('127.0.0.1', 7001)) server.register_introspection_functions() server.register_multicall_functions() server.register_function(addtogether) server.register_function(quadratic) server.register_function(remote_repr) print("Server ready") server.serve_forever() def addtogether(*things): """Add together everything in the list things .""" return reduce(operator.add, things) def quadratic(a, b, c): """Determine x values satisfying: a * x * x + b * x + c = 0""" b24ac = math.sqrt(b*b - 4.0*a*c) return list(set([(-b-b24ac) / 2.0*a, (-b+b24ac) / 2.0*a])) def remote_repr(arg): """return the repr() rendering of the supplied arg """ return arg if __name__ == '__main__': main()
The client code is as follows:
import xmlrpclib def main(): proxy = xmlrpclib.ServerProxy('http://127.0.0.1:7001') print("Here are the functions supported by this server:") print("next calculator addtogether: ") print(proxy.addtogether('x','y','z')) print(proxy.addtogether('x','y','z')) print(proxy.addtogether('x','y','z')) print(proxy.addtogether('x','y','z')) for method_name in proxy.system.listMethods(): if method_name.startswith('system.'): continue signatures = proxy.system.methodSignature(method_name) if isinstance(signatures, list) and signatures: for signature in signatures: print('%s(%s)' %(method_name, signature)) else: print('%s(...)' %(method_name,)) method_help = proxy.system.methodHelp(method_name) #if method_help: # print(' ', methodHelp) print(proxy.addtogether('x','y','z')) print("addtogether result ") if __name__ == '__main__': main()
The above is the detailed content of Teach you how to use the XML library to implement RPC communication functions. For more information, please follow other related articles on the PHP Chinese website!