参考:https://www.cnblogs.com/ExMan/p/10408353.html
用python的rpc库SimpleXMLRPCServer 做测试,创建rpc server,然后注册一些函数,供应别的客户端去调用
rpc_server.py:
from xmlrpc.server import SimpleXMLRPCServer
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x // y
server = SimpleXMLRPCServer(('127.0.0.1', 8080))
print('listening on port 8080')
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()
rpc_client.py:
from xmlrpc.client import ServerProxy, MultiCall
proxy = ServerProxy(('http://127.0.0.1:8080'))
multicall = MultiCall(proxy)
multicall.add(5, 3)
multicall.subtract(5, 3)
multicall.multiply(5, 3)
multicall.divide(5, 3)
result = multicall()
print("5+3=%d, 5-3=%d, 5*3=%d, 5//3=%d" % tuple(result))
RPC本来是单任务的,如果任务相对频繁,可以设置成多线程的默认,你不用在调用threading模块什么的,直接引用:
rpc_thread_server.py:
from xmlrpc.server import SimpleXMLRPCServer
from socketserver import ThreadingMixIn
class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
pass
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x // y
server = ThreadXMLRPCServer(('127.0.0.1', 8080), allow_none=True) # 初始化
print('listening on port 8080')
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()
rpc_client.py不变。
---------------另外-------------------
server = SimpleXMLRPCServer.SimpleXMLRPCServer((srv_conf[‘host’], srv_conf[‘port’]), allow_none=True)
添加allow_none=True
防止出错:xmlrpc.client.Fault: <Fault 1: "<class 'TypeError'>:cannot marshal None unless allow_none is enabled">