1. from xmlrpc.server import SimpleXMLRPCServer
    2. class calculate:
    3. def add(self, x, y):
    4. return x + y
    5. def multiply(self, x, y):
    6. return x * y
    7. def subtract(self, x, y):
    8. return abs(x-y)
    9. def divide(self, x, y):
    10. return x/y
    11. obj = calculate()
    12. server = SimpleXMLRPCServer(("localhost", 8088))
    13. # 将实例注册给rpc server
    14. server.register_instance(obj)
    15. print("Listening on port 8088")
    16. server.serve_forever()

    客户端

    1. from xmlrpc import client
    2. server = client.ServerProxy("http://localhost:8088")
    3. print(server.add(2, 3))

    然后,我们通过 server_proxy 对象就可以远程调用之前的rpc server的函数了。

    >> server.add(2, 3)
    5
    >>> server.multiply(2, 3)
    6
    >>> server.subtract(2, 3)
    1
    >>> server.divide(2, 3)
    0